是否保证将 -1 分配给无符号类型会产生最大值? [英] Is it guaranteed that assigning -1 to an unsigned type yields the maximum value?

查看:66
本文介绍了是否保证将 -1 分配给无符号类型会产生最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些关于这个特定主题的问题,但它们都是关于 C++ 的.

I found a few questions on this particular topic, but they were about C++.

将 -1 转换为无符号类型的可移植性如何?

将 -1 转换为无符号类型

将 -1 赋给 unsigned int 以获得最大值是否安全?

在阅读答案时,这似乎是 C 和 C++ 不同之处之一,这似乎很可能或至少不太可能.

And when reading the answers, it seemed likely or at least not unlikely that this is one of those things where C and C++ differs.

问题很简单:

如果我用 unsigned char/short/int/long var 声明一个变量或使用任何其他无符号类型,如固定宽度、最小宽度等,那么是否保证 var = -1 会将 var 设置为它可以容纳的最大值吗?该程序是否保证打印是"?

If I declare a variable with unsigned char/short/int/long var or use any other unsigned types like fixed width, minimum width etc, is it then guaranteed that var = -1 will set var to the maximum value it can hold? Is this program guaranteed to print "Yes"?

#include <stdio.h>
#include <limits.h>

int main(void) {
    unsigned long var = -1;
    printf("%s\n", var == ULONG_MAX ? "Yes" : "No");
}

推荐答案

是否保证将 -1 赋给无符号类型会产生最大值?

Is it guaranteed that assigning -1 to an unsigned type yields the maximum value?

是的.

此程序是否保证打印是"?

Is this program guaranteed to print "Yes"?

是的.

这是一个转换,从 int -1unsigned long.-1 不能表示为 unsigned long.来自 C11 6.3.1.3p2:

It's a conversion, from int -1 to unsigned long. -1 can't be represented as unsigned long. From C11 6.3.1.3p2:

否则,如果新类型是无符号的,则通过重复加或减一个新类型可以表示的最大值来转换该值,直到该值在新类型的范围内

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

所以我们将一个 (ULONG_MAX + 1) 添加到 -1,我们得到 -1 + (ULONG_MAX + 1) = ULONG_MAX位于 unsigned long 的范围内.

so we add one (ULONG_MAX + 1) to -1 and we get -1 + (ULONG_MAX + 1) = ULONG_MAX which is in range of unsigned long.

这篇关于是否保证将 -1 分配给无符号类型会产生最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆