tags:

views:

239

answers:

6

Although I wouldn't have written it myself, what is the expected result of the following statement where A (guaranteed to zero or positive integer) is greater than 1?

return A || 1;

In many languages, I would expect A to be returned, unless the value of A is zero, in which case 1 would be.

I don't have my C book to hand, but I note that in reality, the value 1 always seems to be returned. Is this a result of compiler optimisation or given the potential ambiguity of the expression, is it that the return value is non-deterministic?

+2  A: 

The expected result is YES (or true)

|| operator returns true value if at least one of its operands is true (2nd operand in your code is obviously true)

Vladimir
Doh! Of course. I think all the rain has turned my brain to mush this afternoon. I was trying to explain it to someone else after I fixed the bug and was too hung up on the value of the numbers.
Roger
The answer has nothing to do with any #defines of `true` or `YES` but only with the result of the expression which is of type int. In this case always 1.
Nikolai Ruhe
+1  A: 

This is straight C (no Objective-C involved). It will always return 1.

Nikolai Ruhe
+18  A: 

The standard says

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

See section 6.5.14 of the standard.

Yuji
Perfect, thanks Yuji
Roger
@Roger: Note that if you want the alternate effect you described, you can get that with `return A ? A : 1;`
caf
A: 

In C, the result of ||, &&, or ! is always 0 or 1, never any other non-zero value, regardless of the values of the operands. That means your A || 1 will always yield 1.

Jerry Coffin
A: 

with C-based languages any nonzero value is true(represented by 1). And if your A is zero it will check the other comparisons if it's an OR comparison

Suffice to say, in your example, whatever the value of A is, will always return 1 even if you are using || 2. with 2 being nonzero, when performed with logical operator OR, will always return true(represented by 1)

Michael Buen
A: 

I believe that the compiler will optimize and not even examine the value of A. Can someone confirm? I was under the impression that with A&&0, A||1, and A||0 (=A&&1), the compiler saves time by recognizing that the expression can be simplified to 0, 1, or A respectively.

prelic