-3

I executed a code in the C language, However I am unable to understand its output.

#include <stdio.h>

int main()
{
    int a=5;
    int b= ++a + 0!=0;
    printf("%d %d",++a, b);
    return 0;
}

The output for the above program is

7 1

I am unable to understand why it is so.

  • 1
    Lookup [operator precedence](https://en.cppreference.com/w/c/language/operator_precedence). The `b` value parses as `((++a) + 0) != 0`.. – dxiv Nov 22 '20 at 04:15
  • When given a problem like this, always ignore the spacing. There is no `0!=0` in that code, but the misleading spacing makes it look like there is. [Another example](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c) is `a --> 0` which is really `a-- > 0`. – user3386109 Nov 22 '20 at 04:37
  • Did you try changing the code a bit to see what happens? changing to `b = 0!=0;` (`b` now `0`) or changing to `b = (++a + 0) != 0;` (`b` now `1`) would reveal what's going on – Elliott Nov 22 '20 at 04:40

1 Answers1

2

Order of operations causes this to be treated as:

int b = (((++a) + 0) != 0);

Therefore:

int b = (6 != 0);

6 isn't 0, so that has a value of true aka 1.

int b = 1;
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173