In the below code:
#include <stdio.h>
int main(void)
{
int i=-3,j=2,k=0,m;
m=++i||++j&&++k;
printf("%d %d %d %d",i,j,k,m);
}
Output:
-2 2 0 1
Why is k = 0? because I think k also gets executed because of && operator?
In the below code:
#include <stdio.h>
int main(void)
{
int i=-3,j=2,k=0,m;
m=++i||++j&&++k;
printf("%d %d %d %d",i,j,k,m);
}
Output:
-2 2 0 1
Why is k = 0? because I think k also gets executed because of && operator?
C uses short circuit-logic - since ++i
isn't zero, it's true, and since it's the left-hand side of an ||
operator, we know no matter what's on the right-hand side, it will result to true. Hence, C (and a bunch of similar languages) don't even bother evaluating the right hand side, and just quickly return true. Since ++k
is never evaluated, k
remains unchanged, and is still 0
after the m=++i||++j&&++k;
statement.