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
CodePudding user response:
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 ofnum1
,0
andnum1
is incremented.- since the left operand if false, the right operand of
&&
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 is2
andnum4
is incremented.- the left operand of this second
&&
operator is true, so the right operand is evaluated num3
is evaluated: the value is-2
andnum3
is incremented.2 && -2
is true, the whole expression evaluates to true, which has typeint
and the value1
in C:ans
receives the value1
.printf
outputs1 -1 -1 2 1
(without a trailing newline)
CodePudding user response:
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.