欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2147483648

程序员文章站 2022-06-15 15:59:49
...

在*上看到了很多关于-2147483648的问题,因为这个数字在计算机中的表现确实和直观的认识不一样

比如:(-2147483648> 0) returns true in C++?

-2147483648 is not a "number". C++ language does not support negative literal values.
-2147483648 is actually an expression: a positive literal value 2147483648 with unary -operator in front of it. Value 2147483648 is apparently too large for the positive side of int range on your platform. If type long int had greater range on your platform, the compiler would have to automatically assume that 2147483648 has long int type. (In C++11 the compiler would also have to consider long long int type.) This would make the compiler to evaluate -2147483648 in the domain of larger type and the result would be negative, as one would expect.

注:2147483648=2^31,等于0x1000 0000 0000 0000
当然上面那种写法是不正确的,实际上
0x1000 0000 0000 0000=-2147483648,这是有符号数

翻译:
-2147483648在计算机中并不是一个严格意义上的数,c++不支持负的字面值。
-2147483648实际上是一个表达式,是一个正值2147483648加上一个一元操作符-,当然对于int来说,2147483648太大了,int最大只能表示到
2^31-1=2147483648-1=2147483647
所以编译器会默认的使用long int(在c++11中编译器也可能使用long long int)

当然我用vs2013试了一下,直接编译都不能通过:

int main()
{
    if (-2147483648 > 0)
        std::cout << "true";
}

错误:
error C4146: unary minus operator applied to unsigned type, result still unsigned
vs直接告诉你,把一元的符号加给一个无符号数,结果还是一个无符号数
所以在vs里面是把这个数变成无符号数了
可是我试了一下 long long
不知道为啥还是报这个错?