-2

In the below code:

#include <stdio.h>

int main(void)
{
    int i=-3,j=2,k=0,m;
    m=++i||++j&&++k;
    printf("%d %d %d %d",i,j,k,m);
}

Output:
-2 2 0 1

Why is k = 0? because I think k also gets executed because of && operator?

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Marco Roberts
  • 205
  • 2
  • 9

1 Answers1

8

C uses short circuit-logic - since ++i isn't zero, it's true, and since it's the left-hand side of an || operator, we know no matter what's on the right-hand side, it will result to true. Hence, C (and a bunch of similar languages) don't even bother evaluating the right hand side, and just quickly return true. Since ++k is never evaluated, k remains unchanged, and is still 0 after the m=++i||++j&&++k; statement.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • he might need to know that [`&&` has higher precedence than `||`](http://en.cppreference.com/w/cpp/language/operator_precedence) therefore the expression is parsed as `(++i) || (++j && ++k)` – phuclv Jul 30 '16 at 11:33