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 && num2is evaluated first:num1is evaluated: it evaluates to the initial value ofnum1,0andnum1is incremented.- since the left operand if false, the right operand of
&&is not evaluated (num2is unchanged`) and the expression is false: num1 && num2is false, so the right operand of||must be evaluated to determine the value of the whole expression:num4is evaluated: the value is2andnum4is incremented.- the left operand of this second
&&operator is true, so the right operand is evaluated num3is evaluated: the value is-2andnum3is incremented.2 && -2is true, the whole expression evaluates to true, which has typeintand the value1in C:ansreceives the value1.printfoutputs1 -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.
