Mae*_*tro 0 c++ undefined-behavior unsigned-integer
我知道使用(访问值)类型为内置整数类型的未初始化的非静态和非全局对象是未定义的行为。
int x; // x is defined inside a function scope for example main
++x;// UB
signed char c = 127; // max positive value for char on my machine
c++; // UB overflowing a signed char.
Run Code Online (Sandbox Code Playgroud)
到这里还可以,但是无符号类型呢?
unsigned char uc = 255; // ok
uc++; // ok c now has the value 0
Run Code Online (Sandbox Code Playgroud)
在这里没问题,因为溢出无符号将丢弃范围之外的位。
因此,只要分配给无符号的任何值都是无害的:
unsigned int x; // local non-static uninitialized
std::cout << x << '\n';// is it UB or OK?
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,设置为无符号的任何(不确定)值都不会导致 UB,所以这样做是错误的吗?
我不关心什么值,x但我认为它不会造成任何伤害。
如果没问题,那么我想编译器可以使用未初始化的无符号非静态非全局对象生成一个随机值。