现代编译器是否在for循环中优化unsigned int的使用?

syn*_*gma 3 c c++ compilation unsigned-integer

请考虑以下代码:

for(unsigned i = 0; i < counter1; i++) {
    for(unsigned j = 0; j < counter2; j++) {
        // some code here
    }
}
Run Code Online (Sandbox Code Playgroud)

使用unsigned int而不仅仅是int在这种情况下有什么好处吗?现代编译器会以某种方式对其进行优化,还是唯一的好处就是更大的尺寸unsigned int

the*_*ker 9

unsigned int在for循环中使用没有任何优势int.使用数字范围的边际收益unsigned int远远超过引入错误的机会.此外,unsigned int使可读性更难.

一个可能引入错误的有趣案例是

for (unsigned int i = foo.Length()-1; i >= 0; --i) ...
Run Code Online (Sandbox Code Playgroud)

正如您可能注意到的,这个循环永远不会结束.一些现代gcc编译器可能会在这种情况下提供警告,但有时却没有.比较signedunsigned值也会出现一些错误.如果你需要额外的空间,最好使用a long而不是unsigned int.

具体谈论编译器优化unsigned int,没有任何收益.

  • 好吧,如果你想在2 ^ 31和2 ^ 32之间运行一个循环,unsigned int更容易使用(特别是如果迭代次数基于用户输入而你希望迭代次数能够得到大). (2认同)