Consider the following:
#include <iostream>
int main() {
unsigned int x = 3;
unsigned int y = 5;
std::cout << "a: " << x - y << std::endl;
std::cout << "b: " << ((int)x) - y << std::endl;
std::cout << "c: " << x - ((int)y) << std::endl;
std::cout << "d: " << ((int)x) - ((int)y) << std::endl;
}
$ g++ -Wconversion -Wall uint_stackoverflow.cc -o uint_stackoverflow && ./uint_stackoverflow
a: 4294967294
b: 4294967294
c: 4294967294
d: -2
I understand why "a" doesn't give the expected result. But why "b" and "c" fail puzzles me. For "b" I thought after casting "x" to "int" the result will be "int" again.
Could you please enlighten me?
edit: Shouldn't the compiler warn? g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Thanks,
Somebody
See Question&Answers more detail:os