我是 C 初学者,我对 C 答案书中的以下示例感到困惑。
在您的系统上查找 unsigned long long 大小的一种方法是键入:
printf("%llu", (unsigned long long) ~0);
我不知道为什么这个语法有效?
在我的系统上,int
是32位,long long
是64位。
我期望的是,由于 0
是整数类型的常量,~0
计算 32 位整数的否定,然后将其转换为 unsigned long long
由转换运算符。结果应该是 232 - 1。
不知何故,~
运算符似乎已经知道它应该作用于 64 位?
编译器是否将此指令解释为 printf("%llu", ~(unsigned long long)0);
?这听起来不对,因为转换和 ~
具有相同的优先级。
最佳答案
Somehow, it looks like the ~ operator already knows that it should act on 64 bits?
这不是 ~
运算符,而是强制转换。以下是根据标准完成整数转换的方式:
6.3.1.3 Signed and unsigned integers
- When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
- Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
- Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
signed int
~0
的值对应于系统上的 -1
,负值的二进制补码表示。它不能用 unsigned long long
表示,因此第一个要点不适用。
第二个要点确实适用:新类型是无符号的,因此 unsigned long long
的 MAX
被添加到 -1
一次以将结果放入 unsigned long long
的范围内。这与将 -1
符号扩展到 64 位具有相同的效果。
关于c - 整数文字的类型和 C 中的 ~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544708/