int a=65;
printf("%c", a);
我在 Ubuntu 上的 GCC 上尝试过,但不知道版本。但它有效,我想知道如何? 因为根据我的说法,char 的大小小于 int,因此它不应该是可能的。
最佳答案
printf
函数具有以下声明:
int printf(const char *format, ...);
第一个参数必须是指向 char
数组的指针,但任何其他参数可以是任何类型,因此如果格式说明符与参数不匹配(尽管它是未定义的行为)。
但是,由于 %c
的预期,这仍然有效。从手册页:
If no l modifier is present, the int argument is converted to an unsigned char, and the resulting character is written. If an l modifier is present, the wint_t (wide character) argument is converted to a multibyte sequence by a call to the wcrtomb(3) function, with a conversion state starting in the initial state, and the resulting multibyte string is written.
从上面的段落来看,%c
实际上需要一个 int
并将其转换为 unsigned char
进行打印。那么,如果是这种情况,为什么传递实际的 char
有效呢?这是因为整数促销。在任何可以使用 int
的地方,任何小于 int
的整数类型都会提升为 int
。由于 printf
是可变参数,它无法检查其参数的类型,因此传递给 printf
的 char
将提升为 int
当函数被调用时。
关于c - int a=65; 如何实现? printf ("%c",a);在 GCC 中使用 C 语言工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009716/