Search code examples
c++visual-studiolong-integersigned

C++ Visual Studio weired behaviour of signed integer


I have some long long constants for boundaries in my calculations. Now I have a weired behaviour because some conditions are not valid because the numbers are "missinterpreted" The first output is the number I wantet to use....in the output you can see that the - sign is removed, so I thought about an underflow, but when I add a 0, so the number is even higher, the output is correct....

I'm using Visual studio 2012

cout<<-2147483648<<endl;
cout<<-2147483649<<endl;
cout<<-21474836480<<endl;
cout<<-21474836490<<endl;
cout<<-214748364800<<endl;
cout<<-214748364900<<endl;

as you can see, in the first 2 lines the - sign is removed

2147483648
2147483647
-21474836480
-21474836490
-214748364800
-214748364900

any Idea whats the problem here?


Solution

  • You should carefully examine a warning messages your compiler gives to you. If your code produces no warnings, then you should increase warning generation level for your compiler. This code on MSVC compiler will produce two warnings:

    warning C4146: unary minus operator applied to unsigned type, result still unsigned

    Which is basically means, that compiler will threat first two values as unsigned int, then apply to it unary minus operator. To solve this problem you should implicitly declare value type:

    cout << -(long long)2147483649 << endl;