九月30
C 語言中 printf 的問題
->
今天有個學妹問我一個 C 程式的問題:下面程式的結果為何?
#include <stdio.h>
int main(void)
{
int age = 20;
printf("You are now %d, and will be %d in one year", age, age++);
return 0 ;
}
int main(void)
{
int age = 20;
printf("You are now %d, and will be %d in one year", age, age++);
return 0 ;
}
自認觀念還不錯的我直接就回答「20, 20」。但沒想到實際跑的答案竟然是「21, 20」,這真是出乎意料的結果啊!
馬上另外測試了其他有 printf 函式的語言,如 Java、PHP,結果也都是正確的「20, 20」,所以不知道是 C printf 的 bug 還是什麼原因,希望有人能解答。
Trackback:

可能是C函式引數堆疊的關係, 你可以查看 MSDN 中 __cdecl 的說明, 也許可以找到答案.
之前看過書上說法是
這情況端看 compiler 在該平台的實作
簡單的說,就是在 C 的標準中並沒有規定 “age++” 一定要在印出 “You are…” 之後再執行,所以請小心這一類的地雷 ^^;
所以改成 age++; printf(”You are now %d, and will be %d in one year”, age); 是比較建議的方式。
唔,上面留言的引號被代換成「」了…XD
[...] « C 語言中 printf 的問題 [...]