c question for beginners [closed]
main()
{
  int x=5,y=3;
  x=x+~y+1;
  printf("%d",x);
}
What would the output be?
If your question was "What does this output?", why didn't you just type it in and test it?
#include <stdio.h>
int main (void) {
    int x=5,y=3;
    x = x + ~y + 1;
    printf ("%d\n", x);
    return 0;
}
This outputs 2 on my system. How about yours?
If you print out y and ~y, you'll get 3 and -4 respectively (on a two's complement architecture).
That's because, with two's complement, you can get the negative of a number by inverting all the bits then adding 1. So ~y + 1 (the tilde means "invert all bits") is effectively -y.
   x + ~y + 1
=  x + (~y + 1)
=  x + (-y)
=  x - y
=  5 - 3
=  2
Aside: I don't think that ISO actually mandates an underlying two's complement architecture for storing numbers so that may not work on all implementations. However, it's been a long time since I saw such a beast. And, to be honest, if you want to get the negative of a number, why wouldn't you just use -y?
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论