-4

I have the following code:

#include <stdio.h>
int main(void)
{

    int a = 0, b = 0, c = 0;
    printf("%d\n", a++ && b++ || c++); //Here, a++ gives 0. Still, c++ is evaluated.
    printf("%d %d %d\n", a, b, c); //Prints 1 0 1

    a = 1, b = 0, c = 0;
    printf("%d\n", a++ || b++ && c++); //Here, a++ gives 1 and only a++ is evaluated.
    printf("%d %d %d\n", a, b, c); //Prints 2 0 0
}

Why is it that when L.H.S. of && gives 0, the R.H.S. of || is evaluated? Whereas in the second case, L.H.S. of || gives 1 and nothing is evaluated beyond that?

user2684198
  • 812
  • 1
  • 10
  • 18

1 Answers1

1

This is because precedence of operators. First && is evaluated, then ||.

printf("%d\n", a++ && b++ || c++);

is equivalent to

printf("%d\n", (a++ && b++) || c++);


printf("%d\n", a++ || b++ && c++);

is equivalent to

printf("%d\n", a++ || (b++ && c++));

Hope that makes it clearer for you.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69