2147483648

在stackoverflow上看到了很多關(guān)于-2147483648的問題,因?yàn)檫@個(gè)數(shù)字在計(jì)算機(jī)中的表現(xiàn)確實(shí)和直觀的認(rèn)識(shí)不一樣

比如:(-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
當(dāng)然上面那種寫法是不正確的,實(shí)際上
0x1000 0000 0000 0000=-2147483648,這是有符號(hào)數(shù)

翻譯:
-2147483648在計(jì)算機(jī)中并不是一個(gè)嚴(yán)格意義上的數(shù),c++不支持負(fù)的字面值。
-2147483648實(shí)際上是一個(gè)表達(dá)式,是一個(gè)正值2147483648加上一個(gè)一元操作符-,當(dāng)然對(duì)于int來說,2147483648太大了,int最大只能表示到
2^31-1=2147483648-1=2147483647
所以編譯器會(huì)默認(rèn)的使用long int(在c++11中編譯器也可能使用long long int)

當(dāng)然我用vs2013試了一下,直接編譯都不能通過:

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

錯(cuò)誤:
error C4146: unary minus operator applied to unsigned type, result still unsigned
vs直接告訴你,把一元的符號(hào)加給一個(gè)無符號(hào)數(shù),結(jié)果還是一個(gè)無符號(hào)數(shù)
所以在vs里面是把這個(gè)數(shù)變成無符號(hào)數(shù)了
可是我試了一下 long long
不知道為啥還是報(bào)這個(gè)錯(cuò)?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容