示例分析
#include<iostream>
#include <stdio.h>
struct Result
{
char c;
char d;
unsigned char e;
};
Result getChar(int x, int y)
{
Result res;
unsigned int a = x;
(a + y > 10) ? (res.c = 1) : (res.c = 2);
res.d = a + y;
res.e = a + y;
return res;
};
int main()
{
Result res1;
res1 = getChar(7, 4);
printf("c1:%d\n", res1.c);
printf("d1:%d\n", res1.d);
printf("e1:%d\n", res1.e);
printf("---------------------\n");
Result res2;
res2 = getChar(7, 3);
printf("c2:%d\n", res2.c);
printf("d2:%d\n", res2.d);
printf("e2:%d\n", res2.e);
printf("---------------------\n");
Result res3;
res3 = getChar(7, -7);
printf("c3:%d\n", res3.c);
printf("d3:%d\n", res3.d);
printf("e3:%d\n", res3.e);
printf("---------------------\n");
Result res4;
res4 = getChar(7, -10);
printf("c4:%d\n", res4.c);
printf("d4:%d\n", res4.d);
printf("e4:%d\n", res4.e);
system("pause");
return 0;
}
運行結果:
上面的代碼邏輯是讓輸入進getChar的x,y進行加和,先把x轉換爲無符號整型的類型,然後再與y進行加和,最後得到的結果存入變量d中,輸出出來,如果d大於10則返回1,如果d小於或等於10則返回2。
那麼問題來了,在第四組的輸入中,d4=-3,是小於10的,但爲什麼c的值確是1呢?
這就要說到無符號整型數據和有符號整型數據的區別和聯繫了。
有/無符號整型數據的定義
- 當無符號數(int)和有符號數(unsignedint)進行算數運算時,有符號數(int)會先轉換爲無符號數(unsignedint),再進行相應的算數運算。
- 無符號整型和有符號整型的區別就是無符號類型可以存放的正數範圍比有符號整型中的範圍大一倍,因爲有符號類型將最高位儲存符號,而無符號類型全都儲存數字。
- 無符號整型不能存儲負數,但存儲的最大值可以擴大一倍。
有/無符號整型數據的轉換
有->無:1)如果無的最高位是1,取補碼;2)如果無的最高位是0,直接保存。
取補碼:1)是正數的話,是其本身;2)是負數的話,符號位不變,其餘各位取反,最後一位加1。
有/無符號整型數據的計算
另外需要知道的是,當表達式中存在有符號類型和無符號類型的變量時,所有的操作數都會自動的轉換爲無符號類型進行計算。
那麼再回到此題中來,當輸入爲(7,-7)的時候,把-7轉換成一個非常大的無符號類型,然後與7相加後,處於一個正好溢出的邊緣,相當於被正好中和了,d爲0了,所以c所返回的還是1。
但當輸入(7,-10)的時候,剩餘的加和結果爲-3,被轉換爲無符號整型,是一個很大很大的數(e = 253),肯定比10大,於是,就出現了第四組的情況,返回的結果爲-3,但c卻是1。