【发布时间】:2021-01-28 09:42:51
【问题描述】:
我发现了一些关于这个特定主题的问题,但都是关于 C++ 的。
How portable is casting -1 to an unsigned type?
converting -1 to unsigned types
Is it safe to assign -1 to an unsigned int to get the max value?
在阅读答案时,这似乎是 C 和 C++ 不同的地方之一。
问题很简单:
如果我用unsigned char/short/int/long var 声明一个变量或使用任何其他无符号类型,如固定宽度、最小宽度等,那么是否可以保证var = -1 将var 设置为它可以容纳的最大值?这个程序是否保证打印“是”?
#include <stdio.h>
#include <limits.h>
int main(void) {
unsigned long var = -1;
printf("%s\n", var == ULONG_MAX ? "Yes" : "No");
}
【问题讨论】:
-
但实际上,它不是 stackoverflow.com/questions/1667963/… 的副本吗?我认为不是,因为您提到了它,但该答案字面意思是
The requirements on unsigned arithmetic guarantee that casting -1 to an unsigned type will produce the largest number possible for the target type,答案也跟着This is the same in C and C++。 -
@KamilCuk 我认为最好保留这一点,因为它只关注 C,而且您的回答非常好,并且通过引用直截了当。
-
@KamilCuk 它甚至明确引用了 C99 标准:
C99, §6.2.5/9所以它对 C 绝对有效。 -
好吧,我们现在有了明确的 C 版本
-
@KamilCuk 我个人不喜欢投票结束 C 问题作为 C++ 问题的欺骗,只是因为 C++ 问题的答案提到它也适用于 C。