用多余的参数调用printf会导致行为不确定吗? [英] Is calling printf with excess arguments undefined behaviour?

查看:168
本文介绍了用多余的参数调用printf会导致行为不确定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是否会产生不确定的行为:

I wonder if this yields in undefined behaviour:

printf("Test %d %s", 123, "abc", "def", "ghi");

格式字符串后的前两个参数与格式字符串匹配,因此可以;但是第3和第4个参数过多,因为不再有相应的格式说明符.

The first two arguments after the format string match the format string, so these are OK; but the 3rd and 4th arguments are in excess because there are no more corresponding format specifiers.

IMHO printf()应该只忽略这些多余的参数,并且不应该包含UB.这是正确的吗?

IMHO printf() should simply ignore these excess arguments and there should be no UB. Is this correct?

推荐答案

是的,此场景由标准明确定义.这是不是不确定的行为.

Yes, this scenario is explicitly defined by the standard. It is not undefined behaviour.

要引用C11标准,请参见第§7.21.6.1章 fprintf()函数

To quote the C11 standard, chapter §7.21.6.1, The fprintf() function

[...]如果在保留参数的同时用尽了格式,则会对多余的参数进行评估(一如既往),否则将被忽略 [...]

[...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored [...]

这篇关于用多余的参数调用printf会导致行为不确定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆