c - int a=65; 如何实现? printf ("%c",a);在 GCC 中使用 C 语言工作?

标签 c gcc compiler-errors char int

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 是可变参数,它无法检查其参数的类型,因此传递给 printfchar 将提升为 int 当函数被调用时。

关于c - int a=65; 如何实现? printf ("%c",a);在 GCC 中使用 C 语言工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009716/

相关文章:

c - 使用消息操作的二进制信号量

c - 十进制到 BASE-26 表示法

c - 在xcode中读取文本文件

c - C 中的 realloc — 确切的行为和用途

用 gcc 编译 .c

c++ - 我想我已经重写了一个虚拟方法,但我仍然得到 : "X must implement the inherited pure virtual method Y"

scala - 使用getOrElse连接两个映射时,类型不匹配编译器错误

c++ - 为什么调用不接受带参数的函数的函数在 C 中编译但在 C++ 中不编译

java - 无法使用 observable 解析方法 handleResponse

c++ - Google Mocked 成员函数中的 std::pair 参数编译失败