Negating the minimal integer result in an overflow in C++

The code below compiles with a warning:

#include <iostream>
#include <limits>
#include <cstdint>

int main()
{  
    int64_t m1 = -std::numeric_limits<int64_t>::min();
    int64_t m2 = -m1;
    
    std::cout << m1 << std::endl << m2 << std::endl << std::numeric_limits<int64_t>::max() << std::endl;
    
    return 0;
}
prog.cc: In function 'int main()':
prog.cc:7:18: warning: integer overflow in expression of type 'long int' results in '-9223372036854775808' [-Woverflow]
    7 |     int64_t m1 = -std::numeric_limits<int64_t>::min();
      |                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

and outputs:

-9223372036854775808
-9223372036854775808
9223372036854775807

Leave a Reply

Your email address will not be published. Required fields are marked *