Home > Mobile >  why does the value of num2 in below expression becomes -1 instead of 0?
why does the value of num2 in below expression becomes -1 instead of 0?

Time:10-09

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 of num1, 0 and num1 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 is 2 and num4 is incremented.
  • the left operand of this second && operator is true, so the right operand is evaluated
  • num3 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)

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.

  • Related