sch*_*312 1 c++ unsigned-integer
这段代码给出了有意义的输出
#include <iostream>
int main() {
unsigned int ui = 100;
unsigned int negative_ui = -22u;
std::cout << ui + negative_ui << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
78
Run Code Online (Sandbox Code Playgroud)
变量negative_ui存储-22,但是是一个unsigned int。我的问题是为什么unsigned int negative_ui = -22u;有效。unsigned int商店如何存储负数?是否节省使用或产生不确定的行为?
我使用的是Intel编译器18.0.3。使用该选项时,-Wall不会发生警告。
附言 我已经读过,如果我给一个无符号变量赋一个负值会怎样?以及为什么unsigned int包含负数
unsigned int商店如何存储负数?
It doesn't. Instead, it stores a representable number that is congruent with that negative number modulo the number of all representable values. The same is also true with results that are larger than the largest representable value.
Is it save to be used or does this yield undefined behaviour?
There is no UB. Unsigned arithmetic overflow is well defined.
It is safe to rely on the result. However, it can be brittle. For example, if you add -22u and 100ull, then you get UINT_MAX + 79 (i.e. a large value assuming unsigned long long is a larger type than unsigned) which is congruent with 78 modulo UINT_MAX + 1 that is representable in unsigned long long but not representable in unsigned.
Note that signed arithmetic overflow is undefined.