Categories
Binary World Excitements Work

Type Casting

Even though I started pro­gram­ming more than 16 years ago and got to used to several different pro­gram­ming languages in the meantime, this is the first time I came across the behaviour shown below.

Assume the following piece of code:

int main(int argc, char *argv[]) {
    int x = -2;
    unsigned int y = 10;
    std::cout << (x * y) << std::endl;
    std::cout << (x - y) << std::endl;
}

I’d have expected something like

-20
-12

but instead it returns

4294967276
4294967284

Obviously, this is a type casting issue. Well, more a kind of pecu­li­ar­ity caused by the C/C++ type hierarchy: The signed integer is promoted to an unsigned int, causing the whole cal­cu­la­tion to be handled this way. Nothing new but quite inter­est­ing for me and some col­leagues, though :)

For more inform­a­tion in C/C++ type casting issues, have a look at the following web page: http://www.learncpp.com/cpp-tutorial/44-type-conversion-and-casting/