如何便携式是铸造-1到一个无符号的类型? [英] How portable is casting -1 to an unsigned type?

查看:106
本文介绍了如何便携式是铸造-1到一个无符号的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日前,href=\"http://www.ddj.com/cpp/184403759\">我碰到这个结构

The other day, I came across this construct:

static_cast<size_type>(-1)

在一些C ++例如code,这很可能(取决于细节,其中 SIZE_TYPE 是)等同于以下C:

in some example C++ code, which is likely (depending on the details of where size_type is from) to be equivalent to the following C:

(size_t)(-1)

据我了解,它的工作原理基于这样的事实,在三三两两-1重新presentation补充算术 11111 ... 1 ,换作许多位作为你,所以这是获得该无符号类型,比如为size_t 可容纳的最大值的快捷方式。但是,我的理解也是C不保证二进制补码将被使用;如果C实现使用一的补,这将是比最大值小于1,并且如果它使用签名大小,这将是刚刚超过一半的最大值。

As I understand it, it works based on the fact that the representation of -1 in twos complement arithmetic is 11111...1, for as many bits as you have, so this is a quick way of getting the maximum value that an unsigned type like size_t can hold. However, my understanding is also that C doesn't guarantee that twos complement will be used; if the C implementation uses one's complement, this will be 1 less than the the maximum value, and if it's using signed magnitude, it will be just over half the maximum value.

有一些皱纹,我很想念这保证了该作品的权利,无论符号整数重新presentation的被使用?它是否C和C之间的差异++(很多奇怪的事情做)?

Is there some wrinkle that I'm missing that insures that this works right regardless of the representation of signed integers being used? Does it differ between C and C++ (many surprising things do)?

推荐答案

这是无符号运算保证的要求是铸造-1到一个无符号的类型会产生数量最大可能的目标类型。 C99,§6.2.5/ 9:......不能再通过将得到的无符号整型psented $ P $一个结果是减少了模比可重新presented的一个最大值大的数目通过将得到的类型。

The requirements on unsigned arithmetic guarantee that casting -1 to an unsigned type will produce the largest number possible for the target type. C99, §6.2.5/9: "...a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type."

这是C和C ++相同的(在C ++标准,类似的措词脚注41发现 - 这不是规范的,但它解释等措辞即是)。

This is the same in C and C++ (in the C++ standard, similar wording is found in footnote 41 -- it's not normative, but it's explaining other wording that is).

这篇关于如何便携式是铸造-1到一个无符号的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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