简体   繁体   English

带铸造的无符号/有符号整数加法

[英]Unsigned/Signed Integer Addition with Casting

In C++, is it guaranteed that if I used the signed & unsigned versions of a fixed-width integer to perform an operation, I will get the same result? 在C ++中,如果我使用固定宽度整数的有符号和无符号版本执行操作,是否可以保证获得相同的结果? That is, if I do: 也就是说,如果我这样做:

uint64_t a = [any number];
uint64_t b = [any number];
uint64_t resultOne = a + b;
uint64_t resultTwo = (uint64_t)(((int64_t) a) + ((int64_t) b));

Is it guaranteed that resultOne and resultTwo would always produce the same output no matter what values I use for a and b? 是否可以保证无论我对a和b使用什么值,resultOne和resultTwo总是会产生相同的输出?

With unsigned types, addition is guaranteed to wrap around: if you add 1 to the maximum uint64_t , you get 0 . 对于无符号类型,可以保证加法会回绕:如果将1与最大uint64_t相加,则得到0

With signed types, in both C and C++, wraparound is undefined behavior: anything could happen, and in practice the compiler can do things you don't expect if you have optimization turned on. 对于C和C ++中的带符号类型,环绕都是未定义的行为:任何事情都可能发生,并且在实践中,如果打开了优化功能,编译器可以执行您不希望的操作。

So no, this is not guaranteed by the standard. 所以不,这不是标准所保证的。

However, many compilers give an option to, as an extension to the standard, guarantee wrapped behavior for signed types, in which case the answer is yes. 但是,许多编译器提供了一个选项,作为对标准的扩展,可以保证有符号类型的包装行为,在这种情况下,答案是肯定的。 For example, see -fwrapv of GCC and Clang. 例如,请参阅GCC和Clang的-fwrapv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM