调用中不匹配的格式/参数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
,但我把这些消息去掉了,因为它们与你的问题没有严格的关系。