0

Here is the code

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

And output: -2, 2, 0, 1

But i don't understand the line m = ++i||++j&&++k; How it get's executed. Someone please explain..Thanks!

Hola
  • 2,163
  • 8
  • 39
  • 87
  • But how m gets increased? – Hola Nov 26 '18 at 07:47
  • `||` and `&&` are logical operators. Their result will always be `1` or `0`, depending on whether the expressions evaluate to non-zero or zero values. So you basically have something like: `if ((++i != 0) || (++j != 0) && (++k != 0)) { m = 1; } else { m = 0; }`. – vgru Nov 26 '18 at 07:48
  • I hope you are aware that nobody would actually write code like that in a real world program. – Jabberwocky Nov 26 '18 at 07:56

2 Answers2

6

Initially you have the 4 variables:

  • i = -3
  • j = 2
  • k = 0
  • m is uninitialized

m = ++i||++j&&++k; is executed left to right. so first one is ++i - I suggest reading about the differences between i++ and ++i - In this case i is increased by 1 and become i=-2

-2 is a true expression, therefore m becomes 1 and the rest of the expression is not evaluated. Because true or anything else is always true anyway. So final outcome:

  • i = -2 (increased)
  • j = 2 (unchanged)
  • k = 0 (unchanged)
  • m is 1 (true)
Igal S.
  • 13,146
  • 5
  • 30
  • 48
2

Logical OR operation (expr1 || expr2) employs short-circuiting behavior. That is, expr2 is not evaluated if expr1 is logical 1 (true).

The expression with logical OR operator evaluate to true if any of the two operands is non-zero.

In this expression:

m = ++i||++j&&++k;
    |_|  |______|
    LHS    RHS

The i is initialized with -3. ++i will evaluate to -2.
-2 is a non zero value hence evaluate to logical true and the RHS part of the expression will not evaluated.

Since the whole expression evaluated to true, the value 1 is assigned to m.

H.S.
  • 11,654
  • 2
  • 15
  • 32