int a = 65如何计算; printf(“%c”,a);在GCC中使用C语言工作? [英] How does int a=65; printf("%c", a); work in c language in GCC?
问题描述
int a=65;
printf("%c", a);
我在Ubuntu的GCC上尝试过,但不知道版本。但这奏效了,我想知道如何?
因为根据我的看法,char的大小小于int的大小,因此应该不可能。
I tried it on GCC on Ubuntu I don't know the version. But it worked and I wish to know how? Because according to me the size of char is smaller than int and hence it shouldn't have been possible.
推荐答案
printf
函数具有以下声明:
int printf(const char *format, ...);
第一个参数必须是指向 char $ c $的指针c>数组,但是任何其他参数都可以是任何类型,因此,如果格式说明符与参数不匹配(尽管是未定义行为),这不是编译器错误。
The first argument must be a pointer to a char
array, but any additional arguments can be of any type, so it's not a compiler error if a format specifier mismatches the parameter (although it is undefined behavior).
但是,由于%c
的预期,该方法仍然有效。在手册页中:
This still works however because of what %c
expects. From the man page:
如果不存在l修饰符,则 int参数将转换为
无符号字符,然后写入结果字符。如果存在l
修饰符,则通过调用wcrtomb(3)
函数将wint_t(宽字符)参数转换为多字节序列的
,转换状态从初始状态
和结果的多字节字符串被写入。
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
是可变参数,因此无法检查其参数类型,因此将 char
传递给<$ c $调用该函数时,c> printf 将被提升为 int
。
From the above passage, %c
actually expects an int
and converts it to an unsigned char
for printing. So if that's the case why does passing an actual char
work? That is because of integer promotions. Any integer type smaller than int
is promoted to int
anyplace an int
can be used. Since printf
is variadic it can't check the types of its arguments, so a char
passed to printf
will get promoted to int
when the function is called.
这篇关于int a = 65如何计算; printf(“%c”,a);在GCC中使用C语言工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!