int型

来源:互联网 发布:mysql官方文档 编辑:程序博客网 时间:2024/04/30 14:38

前段时间遇到的关于int型最大最小值的问题,在论坛中寻得了帮助,记录下以免忘记。

#include <iostream>#define MIN_INT  -2147483648#define MIN_INT2 -2147483647-1#define MAX_INT   2147483647const int max_Int =  2147483647;const int min_Int = -2147483648;using std::cin;using std::cout;using std::endl;using std::boolalpha;int main(){  cout << MAX_INT << " " << MIN_INT  << endl;       // 2147483647  2147483648  cout << MAX_INT << " " << MIN_INT2 << endl;       // 2147483647 -2147483648  cout << max_Int << " " << min_Int  << endl;       // 2147483647 -2147483648  int a = min_Int, b = -1;  cout << "a:" << a << " b:" << b << endl;          // a: -2147483648 b:-1  int A = MIN_INT, B = -1;  cout << "A:" << A << " B:" << B << endl;          // A: -2147483648 B:-1  cout << "-2147483648: " << -2147483648 << endl;   // -2147483648: 2147483648  cout << boolalpha << ((b < (-2147483648 - a))?true:false) << endl;        // false  cout << boolalpha << ((b < (MIN_INT - a))?true:false) << endl;            // false  cout << boolalpha << ((b < (min_Int - a))?true:false) << endl;            // true  cout << boolalpha << ((b < (-2147483647 - 1 - a))?true:false) << endl;    // true  cout << boolalpha << ((b < (MIN_INT2 - a))?true:false) << endl;           // true  return 0;}

感谢@FancyMouse的回答

对于常数-2147483648,编译器理解成先有常数2147483648,再取负,因此已经溢出。 

因此define中应该定义为-2147483647 - 1。

以上为个人理解,如果有不对之处还望大家多多指正。

0 0