Let’s have a look at this code:
1 2 3 4 5 6 7 |
int main() { for(int i{0};i<500;i++) { std::cout<<"This is a big number: "<<i*20000000<<std::endl; } } |
And let’s compile it with g++ using the flag -O3, what’s going to happen? Before answering, let’s have a look at the assembly, shall we?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<strong><span style="color:#ff0000;">L16:</span></strong> movsbl 39(%ebx), %eax <strong><span style="color:#ff0000;">L6:</span></strong> movl %esi, %ecx movl %eax, (%esp) addl $20000000, %edi call __ZNSo3putEc subl $4, %esp movl %eax, %ecx call __ZNSo5flushEv L4: movl $22, 8(%esp) movl $LC2, 4(%esp) movl $__ZSt4cout, (%esp) call __ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_i movl %edi, (%esp) movl $__ZSt4cout, %ecx call __ZNSolsEi movl %eax, %esi movl (%eax), %eax subl $4, %esp movl -12(%eax), %eax movl 124(%esi,%eax), %ebx testl %ebx, %ebx <span style="color:#ff0000;"><strong>je L15</strong></span> cmpb $0, 28(%ebx) <span style="color:#ff0000;"><strong>jne L16</strong></span> movl %ebx, %ecx call __ZNKSt5ctypeIcE13_M_widen_initEv movl (%ebx), %eax movl 24(%eax), %edx movl $10, %eax cmpl $__ZNKSt5ctypeIcE8do_widenEc, %edx <strong><span style="color:#ff0000;">je L6</span></strong> movl $10, (%esp) movl %ebx, %ecx call *%edx subl $4, %esp movsbl %al, %eax <strong><span style="color:#ff0000;">jmp L6 </span></strong> <span style="color:#ff0000;"><strong>L15:</strong></span> call __ZSt16__throw_bad_castv .cfi_endproc |
This is actually only a portion of the whole assembly, what I care to show you is the main loop and what’s […]