I have been looking at some simple C code and the different output from GCC using different optimization levels.
C code
#include <stdio.h>
int main() {
int i = 0;
while(i<10) {
printf("Hello\n");
i++;
}
i = 0;
while(i<10) {
printf("i: %d\n", i);
i++;
}
}
When I compile the code using -Os
or -O2
the first loop works a bit differently. It it decrements instead of incrementing, and it is in two different ways. I am wondering why it decrements instead of incrementing like in the code, and the the small difference between -Os
and -O2
.
-Os compiled
0x400486 <main+6> mov edi,0x40068c
0x40048b <main+11> call 0x400450 <puts@plt>
0x400490 <main+16> dec ebx
0x400492 <main+18> jne 0x400486 <main+6>
-O2 compiled
0x400490 <main+16> mov edi,0x40069c
0x400495 <main+21> call 0x400450 <puts@plt>
0x40049a <main+26> sub ebx,0x1
0x40049d <main+29> jne 0x400490 <main+16>
sub
overdec
otherwise O2 would not have chosen it. – PlasmaHH Mar 11 '14 at 13:03