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

标签 c++ c compilation unsigned-integer

考虑以下代码:

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 编译器可能会在这种情况下提供警告,但有时它们不会。比较 signedunsigned 值时也会出现一些错误。如果您需要额外的空间,最好使用 long 而不是 unsigned int

特别是关于使用 unsigned int 的编译器优化,没有任何收获。

关于c++ - 现代编译器是否优化了 unsigned int 在 for 循环中的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194153/

相关文章:

c++ - std::regex 构造函数抛出异常

c - 访问结构体会导致段错误

compilation - 编译器的信号和错误之间的区别 (sbcl 1.2.4)

windows - 如何在 Windows 上安装 omniORB?

c++ - 如何创建可执行文件以在特定处理器架构(而不是特定操作系统)上运行?

c++ - boost spirit 语义 Action 要求

c++ - 为 Arduino 创建一个库

c++ - 在 C++ 中 if(a=b) 是什么意思?对比 if(a==b)

c - 后缀为 'f' 的双常量用法

c++ - 纬度经度的哈希/ key 创建功能?