-1
#include <stdio.h>

int main()
{ 
    int a = -3, b = 2, c = 0, d;
    d = ++a || ++b && ++c;
    printf("%d %d %d %d", a, b, c, d);
    return 0;
}

The output of program is:

-2 2 0 1

Compiler is evaluating the OR (||) operator before AND (&&) but the AND (&&) operator comes before OR (||) in operator precedence.

Please do explain why this happens.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • 6
    I reopened the question; the use of prefix increment in the example is well-defined (as opposed to those in the "dupe"). Please, don't vote-for-close before you have thought things through. – DevSolar Oct 24 '18 at 07:50
  • 2
    you might want to read up on [short-circuit behavior](https://softwareengineering.stackexchange.com/questions/201896/what-is-short-circuiting-in-c-like-languages) of logical `&&` and `||` – Sander De Dycker Oct 24 '18 at 07:52

1 Answers1

3

Precisely because && has more precedence than ||, the statement:

d = ++a || ++b && ++c;

is equivalent to:

d = ++a || (++b && ++c);

Now, ++a is evaluated and tested first (due to the rules of evaluation order for operator ||). This ends up being -2.

Since it is non-zero, the result is true (1). Therefore, the other part of the expression (++b && ++c) is not evaluated, due to the shortcut mechanics of the || operator.

Consequently, d gets assigned 1.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • Shouldn't ++b&&++c be evaluated first ,since precedence of && is before || – Omkar Kadam Oct 24 '18 at 07:50
  • 2
    @OmkarKadam You mixed up the evaluation order (left to right in this example) and operator precedence ( && ties more than || ). – mch Oct 24 '18 at 07:52
  • Why doesn't the expression in the braces get evaluated first (the &&)? As far as I know, the c compiler evaluates parenthesis before anything else. (i'm still new) – SmarthBansal Jan 25 '19 at 02:03
  • @SmarthBansal There is a special rule for `||` which specifies the left-hand side is evaluated first (and the right-hand side is not evaluated if the condition was already true, see [short-circuit evaluation](https://en.cppreference.com/w/c/language/operator_logical)). Please also see the links I provided with the answer. – Acorn Jan 25 '19 at 11:08