Search code examples
c++ccompilationunsigned-integer

Do the modern compilers optimize unsigned int use in for loops?


Consider the following code:

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

Are there any benefits of using unsigned int instead of just int in this context? Would a modern compiler optimize it somehow or is the only benefit just the larger size of unsigned int?


Solution

  • There is no difference in the compiler result for these loops, because in assembly unsigned integers aren't really treated differently in most cases, except for comparisons. The bugs therainmaker mentions are relevant in other cases though.

    $ 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"
    

    If I use -O0 you'll see a difference when branching:

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