Reputation: 11
The below C program gives output -1
for num2
. I do not understand why. Can somebody help me with it?
#include <stdio.h>
int main(void)
{
int num1 = 0, num2 = -1, num3 = -2, num4 = 1, ans;
ans = num1++ && num2++ || ++num4 && num3++;
printf("%d %d %d %d %d", num1, num2, num3, num4, ans);
return 0;
}
output:
1 -1 -1 2 1
Upvotes: 0
Views: 107
Reputation: 144951
The expression num1++ && num2++ || ++num4 && num3++
is parsed as:
(num1++ && num2++) || (++num4 && num3++)
Both ||
and &&
use shortcut evaluation, meaning that the right operand if and only if the left operand evaluates to false (resp. true).
num1++ && num2++
is evaluated first:num1++
is evaluated: it evaluates to the initial value of num1
, 0
and num1
is incremented.&&
is not evaluated (num2
is unchanged`) and the expression is false:num1++ && num2++
is false, so the right operand of ||
must be evaluated to determine the value of the whole expression:++num4
is evaluated: the value is 2
and num4
is incremented.&&
operator is true, so the right operand is evaluatednum3++
is evaluated: the value is -2
and num3
is incremented.2 && -2
is true, the whole expression evaluates to true, which has type int
and the value 1
in C: ans
receives the value 1
.printf
outputs 1 -1 -1 2 1
(without a trailing newline)Upvotes: 1
Reputation: 4924
If the left side of a logical AND &&
is false, the right side will not be evaluated as the result can be determined as false already.
Upvotes: 0