-2

This is the code :

void main()
{
    clrscr();
    int a=-3 , b=2 , c=0, d;
    d = ++a && ++b || ++c;
    printf("a=%d , b=%d , c=%d, d=%d ",a,b,c,d);
    getch();
}

Output : -2 , 3 , 0 , 1

I am unable to understand that why value of c is not incremented, I think it should be 1 and how come output of d = 1.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • Please note that the answer is *totally* different than if you had asked about the very similar-seeming expression `d = ++a & ++b | ++c;` . – Steve Summit Mar 11 '16 at 13:35

1 Answers1

7

The statement;

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

Is grouped left to right (given the precedence of &&);

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

Hence, when evaluating the &&, since the first operand is true (the ++a), the second is evaluated (the ++b). At this point, the result of this logical AND is true; hence the logical OR is true and its second operand is not evaluated (the ++c).

This behaviour is guaranteed and is commonly known as short circuit evaluation. The wording for this in the standards for C++ and C is listed here, in this answer; briefly reproduced here for C++;

§5.14 Logical AND operator

1 The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

§5.15 Logical OR operator

1 The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

Community
  • 1
  • 1
Niall
  • 30,036
  • 10
  • 99
  • 142