printf
調用中不匹配的格式/參數會導致未定義的行爲。如果你打開警告級別,你的編譯器可能會告訴你。例如,clang
給出了這樣的警告,你的第一個程序:
example.c:5:10: warning: conversion specifies type 'double' but the argument has
type 'int' [-Wformat]
printf("%f", i);
~^ ~
%d
和這些的你的第二個:
example.c:5:10: warning: conversion specifies type 'int' but the argument has
type 'double' [-Wformat]
printf("%d\n",f);
~^ ~
%f
example.c:6:10: warning: conversion specifies type 'double' but the argument has
type 'int' [-Wformat]
printf("%f",i);
~^ ~
%d
這沒有特殊標誌的都沒有。默認情況下,gcc
也會在您的程序中發出警告。例1:
example.c:5: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’
例2:
example.c:5: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’
example.c:6: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’
這兩項編譯器還警告你的printf
隱含的聲明,但在我離開這些消息了,因爲他們沒有嚴格把你的問題。
一般參考;這由'printf'文檔覆蓋。 – bitmask 2012-07-15 18:05:22