按照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/