-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
  • 3,891
  • 5
  • 25
  • 31
Marco Roberts
  • 175
  • 1
  • 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
  • 277,661
  • 50
  • 283
  • 320
  • 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