1

Could you please explain why the following program is giving such outputs?

#include<stdio.h>

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

Output:

i= -2
j=1
k=0
m=1

  • 6
    Were you expecting something different ? I suspect you're being teased by *boolean evaluation short-circuiting* (little google food there). – WhozCraig Mar 13 '20 at 17:50
  • Essentially [What is short circuiting and how is it used when programming in Java? (duplicate)](https://stackoverflow.com/questions/9344305/what-is-short-circuiting-and-how-is-it-used-when-programming-in-java) for C – David C. Rankin Mar 13 '20 at 17:56
  • @WhozCraig Actually I am a novice. I don't know much about these types of calculations. – Shuvo mandol Mar 13 '20 at 18:03
  • 2
    @Shuvomandol No matter what your skill level is, it would help if you can narrow down exactly what you find puzzling. For example, you probably understand why `i` got incremented from `-3` to `-2`. It's a waste of time if we have to explain that to you in our answers if you already know it. – David Grayson Mar 13 '20 at 18:24

1 Answers1

5

Since ++i is essentially true, because it is not 0, therefore the || other part will not be evaluated, since it does not matter at this point, the expression is true. Therefore j and k will not change. true is 1, that is why m is 1.

Eraklon
  • 4,206
  • 2
  • 13
  • 29
  • Could you please explain why ++i is essentially true here? – Shuvo mandol Mar 13 '20 at 18:11
  • `++i` beame `-2`. In C everything which is not `0` considered `true`. So your expression is at this point `true || `. Since `true` OR anything is `true` therefore the `` evaluation is skipped (short circuit). – Eraklon Mar 13 '20 at 18:12
  • Also `&&` (like multiplication) has greater priority then `||` (like addition,) so `++i || (++j && ++k)`. If it would have been `(++i || ++j) && ++k` it would have incremented `k`. – Neil Mar 13 '20 at 19:21