工程師應知道的0x10個問題(12): 整型提升的問題

MuLong PuYang
3 min readMar 12, 2022

--

英文參考網址

A ‘C’ Test: The 0x10 Best Questions for Would-be Embedded Programmers

中文參考網址

C語言測試 應知道的0x10個基本問題

原文翻譯

12. What does the following code output and why?

你認為下方的程式碼將會輸出什麼並且為什麼會這樣輸出?

void foo(void)

{

unsigned int a = 6;

int b = -20;

(a+b > 6) ? puts(“> 6”) : puts(“<= 6”);

}

This question tests whether you understand the integer promotion rules in C — an area that I find is very poorly understood by many developers. Anyway, the answer is that this outputs “> 6”. The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus –20 becomes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently (see reference 2). If you get this one wrong, then you are perilously close to not being hired.

這個問題測試你是否了C語言的解整型提升規則 — 一個我發覺很多開發者都不太了解的領域。不管怎樣,這個答案會輸出“> 6”。這個原因是因為這個有著singed與unsinged型態的表達式所有的運算元被提升為unsigned型態。因此–20變成了一個非常大的正整數並且這個表達式計算出大於6。這是個在嵌入式系統非常重要的點因為unsigned的資料型態應該會被頻繁的使用(看參考2)。如果你答錯了這一題,那麼你已經危險的靠近無法聘僱的邊緣。

注1: integer promotion可以參考以下的維基頁面
整型提升
注2: Reference 2在英文來源裡是以下這個
2. Efficient C Code for Eight-Bit MCUs. ESP November 1988

自我實作以及理解

注1: 以下是我的自我實作以及理解的部分,不保證正確而且很有可能描述不清楚或者是有錯誤,讀者若發現有可以更正的地方也歡迎留言告訴我注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異

這裡我們直接照著原文來看結果會是怎樣,是否都被提升為unsigned int

輸出結果真 > 6,所以確實都被提升為正整數

> 6

我們再多測一個項目,這裡我們將a改為整數,設成20,將b改成unsigned int,設成-30

輸出結果為 > 20,代表確實都被設為正整數

> 20

--

--