tags:

views:

95

answers:

1
main()
{
  int x=5,y=3;
  x=x+~y+1;
  printf("%d",x);
}

What would the output be?

+4  A: 

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?

paxdiablo
drat. it outputs 5 on mine
aaronasterling
how is the output 2?
bandana
@Aaron, what machine are you using (or was that some humour that just went whooshing past me)? :-)
paxdiablo
thanx a ton pax
bandana
@paxdiable whoosh.... ;)
aaronasterling