強(qiáng)制轉(zhuǎn)換也是不行的!
示例代碼是:
#include <stdio.h>
int main(int argc,char **argv)
{
? ? int a = 100 ;
? ? short b = (short)a ;
? ? printf("%d\n",b);
? ? return 0;
}
以上本身在short數(shù)據(jù)類型就沒有溢出,而當(dāng)a 賦值本身就很大時一樣會報錯。
如:
#include <stdio.h>
int main(int argc,char **argv)
{
? ? int a = 10000000000000 ;
? ? short b = (short)a ;
? ? printf("%d\n",b);
? ? return 0;
}
運(yùn)行結(jié)果
index.cpp: In function 'int main(int, char**)':
index.cpp:6:13: warning: overflow in implicit constant conversion [-Woverflow]
? ? ?int a = 10000000000000 ;
? ? ? ? ? ? ?^~~~~~~~~~~~~~
-24576
2022-12-30
int是4個字節(jié),32位bit(1位符號+31位數(shù)字),取值范圍(+2,147,483,647? ?~? -2,147,483,648),你的變量int a = 10000000000000 大于int的上界所以報錯;