Reputation: 23
I do not understand why before if-statement ++b[1] is equal to 1, but after if-statment ++b[1] is equal to 0. Why ++b[1] does not increase inside if-statement?
#include <stdio.h>
int main()
{
int c = 0;
int b[3] = {4};
printf("%d\n", ++b[1]); // return 1
b[1]--;
if((c-- && ++b[1])|| b[0]++)
{
printf("%d\n", b[1]); // return 0
printf("%d\n", c); // return -1
}
return 0;
}
Upvotes: 2
Views: 132
Reputation: 29690
There's just some confusing operator usage going on here.
c--
is a postfix decrement, and so in the conditional statement c
is evaluated as false (as it is 0
), before being decremented. &&
short circuits and only evaluates the second condition if the first is true, we do not evaluate ++b[1]
, but enter the conditional on the truthiness of b[0]++
. Upvotes: 2
Reputation: 2969
if((c-- && ++b[1])|| b[0]++)
c--
yields 0
, so ++b[1]
is not evaluated.
This is called short-circuit evaluation.
Upvotes: 3