How to see the code generated by the compiler

The guys in one of the excersises (ch.5, e.8) from TC ++ PL Bjarne asks to do the following:
“Run some tests to check if your compiler really generates equivalent code to iterate using pointers and iterating through indexing. If you can request different degrees of optimization, see if and how it affects the quality of the generated code. "

Any idea how it is and with what? Thanks for the consultation.

+3
source share
2 answers

You want to write code something like this:

int a[] = {1,2,3,4};
int n = 0;
for ( int i = 0; i < 4; i++ ) {
   n += a[i];
}

int * p = a;
for ( int i = 0; i < 4; i++ ) {
   n += *p++;
}

, . , .

+5
int sum_with_array_indexing(int* p, int size)
{
    int s = 0;
    for (int i = 0; i < size; ++i)
    {
        s += p[i];
    }
    return s;
}

int sum_with_pointer_arithmetic(int* p, int size)
{
    int s = 0;
    for (int i = 0; i < size; ++i)
    {
        s += *p++;
    }
    return s;
}

g++ -S -O2 :

__Z23sum_with_array_indexingPii:
LFB0:
    pushl   %ebp
LCFI0:
    movl    %esp, %ebp
LCFI1:
    pushl   %ebx
LCFI2:
    movl    8(%ebp), %ebx
    movl    12(%ebp), %ecx
    testl   %ecx, %ecx
    jle L8
    xorl    %edx, %edx
    xorl    %eax, %eax
    .p2align 2,,3
L4:
    addl    (%ebx,%edx,4), %eax
    incl    %edx
    cmpl    %ecx, %edx
    jne L4
L3:
    popl    %ebx
    leave
    ret
L8:
    xorl    %eax, %eax
    jmp L3

__Z27sum_with_pointer_arithmeticPii:
LFB1:
    pushl   %ebp
LCFI3:
    movl    %esp, %ebp
LCFI4:
    pushl   %ebx
LCFI5:
    movl    8(%ebp), %ebx
    movl    12(%ebp), %ecx
    testl   %ecx, %ecx
    jle L15
    xorl    %eax, %eax
    xorl    %edx, %edx
    .p2align 2,,3
L12:
    addl    (%ebx,%edx,4), %eax
    incl    %edx
    cmpl    %ecx, %edx
    jne L12
L11:
    popl    %ebx
    leave
    ret
L15:
    xorl    %eax, %eax
    jmp L11
+3

Source: https://habr.com/ru/post/1739587/


All Articles