为什么 printf 中缺少的参数不会产生错误 [英] Why doesn't a missing parameter in printf produce an error
本文介绍了为什么 printf 中缺少的参数不会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中 -
int main() {
// your code goes here
int a=10,b=20,c=30;
printf("%d %d %d\n",a,b,c);
printf("%d %d %d %d %d %d\n",a,b,c);
return 0;
}
输出在各自的位置包含 10,20 和 30,但剩余的 %d 格式说明符输出垃圾值.如果我们没有指定所需的参数数量,为什么它不会给出错误?这有时有用吗?
the output contains 10,20 and 30 in their respective positions, but the remaining %d format specifiers output garbage values. Why doesn't it give an error if we don't specify the required number of parameters? Is this useful sometimes?
代码链接:ideone
推荐答案
It's 未定义 如果您传递的参数少于格式说明符.编译器不需要对未定义的行为产生任何错误.
It's undefined if you pass fewer arguments than the format specifiers. Compiler is not required to produce any errors on undefined behaviour.
虽然,大多数编译器都会这样做.例如,GCC 会为您的代码生成以下内容:
Although, most compilers would do. GCC, for example, produces the following for your code:
warning: too few arguments for format
编译时:
gcc -Wall -Wextra -std=c99 file.c
这篇关于为什么 printf 中缺少的参数不会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文