考虑以下代码:
for(unsigned i = 0; i < counter1; i++) {
for(unsigned j = 0; j < counter2; j++) {
// some code here
}
}
在这种情况下使用 unsigned int
而不是仅仅使用 int
有什么好处吗?现代编译器会以某种方式优化它,还是唯一的好处只是更大的 unsigned int
?
最佳答案
与 int
相比,在 for 循环中使用 unsigned int
没有任何优势。使用 unsigned int
的数字范围的边际 yield 远远超过引入错误的机会。此外,unsigned int
增加了可读性。
一个可能引入错误的有趣案例是
for (unsigned int i = foo.Length()-1; i >= 0; --i) ...
您可能会注意到,这个循环永远不会结束。一些现代 gcc 编译器可能会在这种情况下提供警告,但有时它们不会。比较 signed
和 unsigned
值时也会出现一些错误。如果您需要额外的空间,最好使用 long
而不是 unsigned int
。
特别是关于使用 unsigned int
的编译器优化,没有任何收获。
关于c++ - 现代编译器是否优化了 unsigned int 在 for 循环中的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194153/