-1

I want so see the values of the four variables (Basically checking the precedence order of logical operators).

#include<stdio.h>
int main()
{
    int a=0, b=-7, c=0, d;
    d = ++c || ++a && ++b  ;
    printf("\n %d %d %d %d",a,b,c,d);
}

I expect the result to be '0 -6 1 1', but the actual output is '0 -7 1 1'. Can anyone please give an explanation behind the output shown?

1 Answers1

2

First have a look at Operator Precedence.

Then, regarding the working of logical OR operator, from C11, chapter ยง6.5.14 (emphasis mine)

[...] the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

and regarding the result:

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

So, in your code

 d = ++c || ++a && ++b  ;

is the same as

 d = (++c) || (++a && ++b);

which evaluates to

 d = 1 || (++a && ++b);         // short circuit, RHS not evaluated

which is finally same as

d = 1;  // 1 is not the value computation of `++c`, rather result of the `||` operation.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    I agree is not `d = ++c;` but replacing `d = ++c || ++a && ++b ;` by `d=1;` does not explain why _c_ becomes 1 โ€“ bruno May 27 '19 at 08:41
  • @bruno What do you mean, I cannot understand you clearly โ€“ Sourav Ghosh May 27 '19 at 08:49
  • 1
    you are focused to explain why `(++a && ++b)` is not executed, and in a way 'forget' the modification of _c_, you do like if _c_ was initialized to 1 and not modified, the OP needed help and may be better to explain all, just my 2 cents ;-) โ€“ bruno May 27 '19 at 09:21