Prefix vs postfix in a for loop

Viewed 569

In a for loop, because the last (update) expression cannot involve assignment, is it trivial whether it uses prefix or postfix increments/decrements? For example:

for (int i=0; i < 10; i++) {...}

vs.

for (int i=0; i < 10; ++i) {...}

Would there ever be a case where doing a prefix or postfix would matter in the update expression of a for loop?

1 Answers

It makes no difference. Prefix vs. postfix on the int loop variable produces identical assembly. I tested both loop forms on https://godbolt.org/ with a loop body that call printf("%d\n", i) on x86-64 gcc.

The prefix form for (int i=0; i < 10; ++i) {...} produces:

        mov     DWORD PTR [rbp-4], 0      ; Set i = 0.
.L3:
        cmp     DWORD PTR [rbp-4], 9      ; Compare i vs. 9.
        jg      .L4                       ; Exit the loop if i > 9.
        (... Loop body code ...)
        add     DWORD PTR [rbp-4], 1      ; Increment i.
        jmp     .L3                       ; Jump back o L3.
.L4:

The postfix form for (int i=0; i < 10; i++) {...} produces identical assembly (aside from a cosmetic difference in jump label names):

        mov     DWORD PTR [rbp-4], 0      ; Set i = 0.
.L7:
        cmp     DWORD PTR [rbp-4], 9      ; Compare i vs. 9.
        jg      .L8                       ; Exit the loop if i > 9.
        (... Loop body code ...)
        add     DWORD PTR [rbp-4], 1      ; Increment i.
        jmp     .L7                       ; Jump back to L7.
.L8:

And the result is the same even if I disable the optimizer (compile flag -O0). So it isn't the case that one form gets optimized into the other.

Related