c - printf ("%x",1) 是否调用未定义的行为?

标签 c printf standards language-lawyer variadic-functions

按照C标准(6.5.2.2第6段)

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. If the number of arguments does not equal the number of parameters, the behavior is undefined. If the function is defined with a type that includes a prototype, and either the prototype ends with an ellipsis (, ...) or the types of the arguments after promotion are not compatible with the types of the parameters, the behavior is undefined. If the function is defined with a type that does not include a prototype, and the types of the arguments after promotion are not compatible with those of the parameters after promotion, the behavior is undefined, except for the following cases:

  • one promoted type is a signed integer type, the other promoted type is the corresponding unsigned integer type, and the value is representable in both types;
  • both types are pointers to qualified or unqualified versions of a character type or void.

因此,一般来说,将 int 传递给需要 unsigned int 的可变参数函数并没有错(反之亦然),只要传递的值是适合两种类型。但是,printf 的规范如下(7.19.6.1 第 9 段):

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

有符号/无符号不匹配也不异常(exception)。

这是否意味着 printf("%x", 1) 调用了未定义的行为?

最佳答案

我相信它在技术上是未定义的,因为 %x 的“正确类型”指定为 unsigned int - 正如您所指出的,此处有符号/无符号不匹配也不异常(exception)。

printf 的规则是针对更具体的情况,因此会覆盖一般情况的规则(对于特定覆盖一般情况的另一个示例,通常允许将 NULL 传递给需要 const char * 参数的函数,但它是未定义的行为将 NULL 传递给 strlen() )。

我说“技术上”,因为我认为考虑到标准中的其他限制,实现需要有意地反常才能导致这种情况出现问题。

关于c - printf ("%x",1) 是否调用未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4664100/

相关文章:

c++ - 如何判断您的编译器支持哪个版本的 ISO C++ 标准?

javascript - 什么时候*不*使用内置的新作品?

c - GNU ld --undefined 选项有什么作用?

谁能说采样率和帧大小是如何相关的?

c++ - 如何在没有套接字管理的情况下使用 OpenSSL 库?

c - 如何正确计算互相关?

c - 我们如何将包含预定义宏的字符串存储到 C 中的变量中?

c - 在 GNU 系统中使用 printf 打印 size_t

c - 我需要多大的缓冲区?

用于复杂查询的 REST API