现代编译器是否优化了for循环中使用的无符号int



考虑以下代码:

for(unsigned i = 0; i < counter1; i++) {
    for(unsigned j = 0; j < counter2; j++) {
        // some code here
    }
}

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

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

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

for (unsigned int i = foo.Length()-1; i >= 0; --i) ...

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

特别是谈到使用unsigned int的编译器优化,没有任何好处。

这些循环的编译器结果没有区别,因为在汇编中,除了比较之外,大多数情况下对无符号整数的处理并没有什么不同。不过,治疗师提到的虫子在其他情况下也是相关的。

$ cat test.c
#include <stdlib.h>
#include <stdio.h>
int main(void) {
    unsigned buffer[100][100];
    for (unsigned i = 0; i < 100; i++) 
        for (unsigned j = 0; j < 100; j++)
            fprintf(stdout, "i");
}
$ sed s/unsigned/int/ test.c  > testint.c
$ gcc -std=c11 -O3 testint.c -S; gcc -std=c11 -O3 test.c -S
$ diff test.s testint.s
1c1
<   .file   "test.c"
---
>   .file   "testint.c"

如果我使用-O0,你会看到分支时的差异:

$ diff test.s testint.s
1c1
<   .file   "test.c"
---
>   .file   "testint.c"
27c27
<   jbe .L4
---
>   jle .L4
31c31
<   jbe .L5
---
>   jle .L5

相关内容

最新更新