看板 C_and_CPP 關於我們 聯絡資訊
其實這是一個老梗,爬文之後,Test 1有人提出來講,Test 2好像沒有, 再加上小弟我最近查資料的時候,偶然在Jserv's Blog發現的有趣差異, 於是乾脆通通都PO上來分享,直接看程式碼: Test 1: #include <stdio.h> int main() { printf("%d, %d\n", sizeof('J'), sizeof(char)); return 0; } Compiler & Output 1-1: [Use GNU C Compiler] $ gcc -o sizeof sizeof.c $ ./sizeof 4, 1 Compiler & Output 1-2: [Use GNU C++ Compiler] $ g++ -o sizeof sizeof.c $ ./sizeof 1, 1 Explain: [From Jserv's Blog] C++ 中 sizeof('J') 等同於 sizeof(char),所以我們看到輸出 "1", 但是對於 C 語言來說, 有著 "default to int" 的語意,所以等同於計算 sizeof(int), 又在 32-bit 硬體架構來說,大致會輸出 "4", 而 C# 與 C++ 對此有類似的表現,不過還是得考慮 sizeof('x') 或 sizeof(L'x') 的不同行為(多國語文的 multi-character)。 Test 2: #include <stdio.h> struct Empty { } empty; int main() { printf("sizeof(empty) = %d\n", sizeof(empty)); return 0; } Compiler & Output 2-1: [Use GNU C Compiler] $ gcc -o sizeof sizeof2.c $ ./sizeof sizeof(empty) = 0 Compiler & Output 2-2: [Use GNU C++ Compiler] $ g++ -o sizeof sizeof2.c $ ./sizeof sizeof(empty) = 1 Explain: [The description in C++ standard language] A class with an empty sequence of members and base class objects is an empty class. Complete objects and member subobjects of an empty class type shall have nonzero size. 資料出處:http://blog.linux.org.tw/~jserv/archives/001876.html ~以上,下台一鞠躬~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.251.71.22 ※ 編輯: shiengchyi 來自: 60.251.71.22 (04/20 10:57)