Type Casting

Type Casting

Even though I started programming more than 16 years ago and got to used to several different programming 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 peculiarity caused by the C/C++ type hierarchy: The signed integer is promoted to an unsigned int, causing the whole calculation to be handled this way. Nothing new but quite interesting for me and some colleagues, though :)

For more information 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/

One thought on “Type Casting

  1. baobab

    hi !

    you would probably have expected :

    -20
    +12

    anyway, you still have a typ(e cast)ing issue…