c陷阱之無符號與有符號變數進行比較
作者:由 技術老兵 發表于 遊戲時間:2022-02-21
#include
int
array
[]
=
{
23
,
24
,
22
,
21
,
20
,
11
,
1
,
112
};
#define TOTAL_ELEMENTS ((sizeof(array)/sizeof(int)))
int
main
(
void
)
{
int
d
=-
1
,
x
=
0
;
if
(
d
<=
TOTAL_ELEMENTS
-
2
){
x
=
array
[
d
+
1
];
}
printf
(
“%d
\n
”
,
x
);
}
以上程式碼的執行結果x=0?
由於TOTAL_ELEMENT返回的是無符號整數,當表示式進行比較時, d被編譯器升級為unsigned int型別,-1轉換為無符號整數將是一個非常大的正整數,以至於表示式的值為假,導致x值為0。
要解決以上問題,只需要把TOTAL_ELEMENT顯式的轉換為有符號數,即可得到預想的結果x=23
#include
int array[] = {23,24,22,21,20,11,1,112};
#define TOTAL_ELEMENTS ((sizeof(array)/sizeof(int)))
int main(void)
{
int d=-1,x=0;
if(d <= (int)TOTAL_ELEMENTS -2){
x=array[d+1];
}
printf(“%d\n”,x);
}