是 "printf("%d\n",(int)a);" unsigned int 的未定义行为?

Is "printf("%d\n",(int)a);" undefined behaviour for unsigned int?

如果我像这样使用错误的格式说明符:

unsigned int i = -1;
printf("%d\n", i);

它被调用 未定义的行为 因为 %u 格式说明符 unsigned.

C11 标准 § 7.21.6.1(P9):

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

但是,如果我这样写:

unsigned int i = -1;
printf("%d\n", (int)i); // unsigned to signed 

这也是未定义的行为吗?

Is it also undefined behavior?

没有。参数类型正确。它需要一个带符号的整数,而您提供了一个。唯一需要注意的是,结果是实现定义的(不是未定义的)。

6.3.1.3 Signed and unsigned integers - p3

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

所以要么它会打印一些东西(因为转换发生了),要么会发出一些信号。无论发生什么,您的实施都需要通过记录让您知道。