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
yields identical code:
__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
and:
__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