gpt4 book ai didi

c++ - 我可以在 printf 中需要整数的地方传递一个字符吗?

转载 作者:IT老高 更新时间:2023-10-28 22:11:22 25 4
gpt4 key购买 nike

下面的代码正确吗?

char mychar = 200;
printf("%x", mychar);

根据http://www.cplusplus.com/reference/clibrary/cstdio/printf/ %x 需要一个整数(我的编译器为 4 个字节),我在这里只传递 1 个字节。由于 printf 使用 varargs,我担心这仅适用于堆栈上的字节对齐(即,当压入堆栈时 char 始终使用 4 个字节)。

我觉得这样写比较好:

char mychar = 200;
printf("%x", static_cast<int>(mychar));

你认为第一个代码是安全的吗?如果不是,你认为如果我切换到 bigendian 架构,我会得到不同的输出吗?

最佳答案

在您的示例中,参数实际上是 int 类型。由于 默认参数提升mychar 被提升为 int

(C99, 6.5.2.2p6) "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."

和(强调我的):

(C99, 6.5.2.2p7) "If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments."

请注意,从技术上讲,x 转换说明符需要 unsigned int 参数,但 intunsigned int 类型是保证具有相同的表示。

关于c++ - 我可以在 printf 中需要整数的地方传递一个字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11432051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com