gpt4 book ai didi

c++ - 意外的宏观评估

转载 作者:太空狗 更新时间:2023-10-29 20:54:06 25 4
gpt4 key购买 nike

为什么打印 ffffffff

#define MYMACRO(n) (((uint16_t)0 - 1) >> (16 - (n)))
std::cout << std::hex << MYMACRO(1);

当打印 1 时?

#define MYMACRO(n) (((uint32_t)0 - 1) >> (32 - (n)))
std::cout << std::hex << MYMACRO(1);

我用 GCC 和 cpp.sh 试过了。

最佳答案

解释在 type-promotion-in-c 中.

(§6.3.1.1 Boolean, characters, and integers):

If an int can represent all values of the original type, the value is converted to an int; ... These are called the integer promotions. All other types are unchanged by the integer promotions.

因此对于您的第一种情况,((uint16_t)0 - 1) 被转换为 int 以满足减法的需要。所以右移操作是算术右移而不是逻辑右移。

关于c++ - 意外的宏观评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313898/

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