C/C++ sizeof的陷井

猜猜看下面的程式輸出結果如何?

int a = 0;
cout << sizeof(a = 10) << endl;
cout << a << endl;

答案是4及0,答錯了吧。

其實很簡單,假如你知道sizeof是在編譯時期(compile time)就決定值的話,就可以知道正確答案是多少。

;

再來看看下面這個程式輸出是什麼。

struct A {
};

printf("%d\n", sizeof(struct A));

答案可能是0,也可能是1。怎麼說?

如果程式是C語言編譯器編譯,那麼輸出會是0。如果程式是C++編譯器編譯,那麼輸出是1。

Standard C++ language definition定義如下:
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.

根據C++的定義,一個空類別的大小不能為0,至少會是1。這是C和C++定義不同的地方。

留言

這個網誌中的熱門文章

以lex/yacc實作算式計算機

猜數字遊戲 (電腦猜人)

KillSudoku 4顆星精彩數獨詳解 - 鍊技巧