由于转换,C++ 换位换行?

C++ bitshift wraps due to conversion?

有人可以解释这种行为吗?

#include <iostream>
using namespace std;
int main(){
    for(int i = 0; i <= 32; i++){
        unsigned long test = 1u << i;
        cout << test << endl;
    }
}

输出:

1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648
1

直到最后才有意义。位移位运算符不应该换行,但在这里它似乎就是这样做的。我想这是因为文字“1u”是比无符号长整型更小的类型。使用“1ul”代替会使行为完全正常,因此类型转换一定有问题,但我很想知道到底是什么以及为什么!

如果按位移位的右操作数的值为负或大于或等于提升的左操作数中的位数,则行为未定义。

来自https://timsong-cpp.github.io/cppwp/n3337/expr.shift#1

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

而且解释未定义行为的行为是没有意义的,因为它是未定义的。