-3

I've found this question somewhere and couldn't understand it. Please help me out with this.

#include<stdio.h>

    int main(){

    char x = 250;

    int ans = x + !x + ~x + ++x;

    printf("%d", ans);


}

The output comes out to be -6. I don't understand how the compiler performs operation.

Thanks in advance!

  • 1
    If that `char` is signed, note that `250` is out of range but could be `-6`. But the `++x` without a sequence point makes it *undefined behaviour*. – Weather Vane Mar 21 '17 at 18:31

1 Answers1

0

When you're trying to understand something like this, it's often helpful to break the problem down into smaller pieces and look at each one. I modified your program so that it prints each of the values:

#include<stdio.h>

int main(){

    char x = 250;

    printf("x:   %d\n", x);
    printf("!x:  %d\n", !x);
    printf("~x:  %d\n", ~x);
    printf("++x: %d\n", ++x);

    int ans = x + !x + ~x + ++x;

    printf("ans: %d\n", ans);
}

And the output I get when I run it is:

x:   -6
!x:  0
~x:  5
++x: -5
ans: -5

Once you understand what each part means, it's easier to see how they combine into the final result. However, my compiler also emits a warning because ++x modifies x in the same expression that uses x in other places, and changing the order in which the terms are evaluated will change the final result.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • 1
    Even though this advice is helpful, your answer gives the impression that the blend of operations describes defined behaviour. It doesn't (at least not when combined erratically). – byxor Mar 21 '17 at 18:42