如何可移植将-1投放到未签名类型? [英] How portable is casting -1 to an unsigned type?

查看:93
本文介绍了如何可移植将-1投放到未签名类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一天,我遇到了这个结构:

  static_cast< size_type>( -  1)

示例C ++代码,这很可能(取决于 size_type 的来源)的细节等同于以下C:

 (size_t)( -  1)



我理解它,它的工作原理基于这样的事实,二进制补码算术中的表示形式是 11111 ... 1 ,尽可能多的位,因此这个是获取一个无符号类型如 size_t 可以保存的最大值的快速方法。但是,我的理解是,C不保证将使用二进制补码;如果C实现使用一个补码,这将是最小值的1,如果它使用签名的幅度,它将刚刚超过最大值的一半。



有没有一些皱纹,我缺少,以确保这种工作正确,无论使用的有符号整数的表示形式?它是不同的C和C ++(许多令人惊讶的事情做)?

解决方案

无符号算术的要求保证铸造-1无符号类型将产生目标类型的最大可能数。 C99,§6.2.5/ 9:...无法由所得到的无符号整数类型表示的结果以大于可以由结果类型表示的最大值的一的数减少。

这在C和C ++中是相同的(在C ++标准中,类似的措辞在脚注41中找到 - 它不是规范性的,但它解释了其他的措辞) / p>

The other day, I came across this construct:

static_cast<size_type>(-1)

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)

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.

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)?

解决方案

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."

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天全站免登陆