-2
unsigned u = 10;
int i  = -42;
std::cout<<u+i<<std::endl; 

for a 32 bit integer it prints 4294967264 But I am not able to understand it how it works.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
vyasriday
  • 90
  • 1
  • 9
  • 1
    In an operation involving and `unsigned int` and an `int`, the `int` operand gets converted to `unsigned int` first, which in this case results in a very large number when `-42` is converted (re-interpreted, really) to `unsigned int`. – njuffa Dec 05 '16 at 15:27
  • What happen is an [*implicit conversion*](http://en.cppreference.com/w/cpp/language/implicit_conversion), more specifically an [integral converison](http://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions) where the signed value is converted to an unsigned. – Some programmer dude Dec 05 '16 at 15:28
  • What did you expect instead? – Lightness Races in Orbit Dec 05 '16 at 15:30
  • @LightnessRacesinOrbit I'm gonna go out on a limb here and say -32. – jaggedSpire Dec 05 '16 at 15:31
  • @jaggedSpire: It is for the OP to explain their expectation, and annotate how they maintained that expectation in the face of the research they performed. – Lightness Races in Orbit Dec 05 '16 at 15:35
  • @LightnessRacesinOrbit I was unable to understand the output of the code. – vyasriday Dec 05 '16 at 16:01
  • Yes, you said that already. What did you expect instead? And why? Work with us. – Lightness Races in Orbit Dec 05 '16 at 16:06
  • @LightnessRacesinOrbit I expected it to be -32 and then it's unsigned conversion and that is what happened here but I was not able to get to the value 4294967264. Maybe I was doing it differently which was wrong. – vyasriday Dec 05 '16 at 16:28
  • @HRIDAYESHSHARMA: When you worked it out on paper, how did you perform the unsigned conversion? Not sure why you expected -32 when you know an unsigned conversion is going to take place. The value you get is simply 32 underneath the maximum value of your unsigned integer! – Lightness Races in Orbit Dec 05 '16 at 17:02
  • @LightnessRacesinOrbit I thought it to be -32 and the result will be unsigned conversion of -32 which was I guess what the actual answer was – vyasriday Dec 05 '16 at 17:06

3 Answers3

1

looks like its treating i as an unsigned integer. i is stored as '11111111111111111111111111010110' in twos compliment form. This is equivalent to 4294967254 when interpreted as an unsigned integer. when you add 10 to it, you get the final answer of 4294967264

0

Short answer: All 32 bits of int i was "converted" to unsigned and the result of u+i is an unsigned int, take a look at this and this

Solution:

  1. Use int u instead of unsigned u

  2. Use type-cast:

    • int(u + i)
    • int(u) + i
Community
  • 1
  • 1
DMaster
  • 603
  • 1
  • 10
  • 23
-1

4294967264 - 2^32 = -32. Does that look familiar? It should, since -32 = 10 - 42

Jonathan Wheeler
  • 2,539
  • 1
  • 19
  • 29