Search code examples
cstackintunsigned

Casting to an unsigned int, then casting back, C


If I have a stack S, filled with signed ints, I want to do the following: POP two values and cast it to an unsigned int, then add them together, and then push back a SIGNED sum. I did the following, but I don't know if it's correct:

unsigned int x = (unsigned int)pop(S)
unsigned int y = (unsigned int)pop(S)
int sum = x+y
push(S, sum);
pc++

Am I on the right track? Also, can someone explain to me a little bit about explicit casting? Thank you.


Solution

  • You are correct in the sense that your code does precisely what you say it should do. The real question is whether or not that is what you are looking to achieve.

    A negative number cast to unsigned int becomes a very large positive number. For example, negative one becomes the largest positive integer that can be expressed in an unsigned int after the cast to unsigned (try it!) When you add two negative numbers that were cast to unsigned, you are guaranteed to get an overflow. If that is indeed what you are trying to do, your code is definitely doing it.