Original Post
I was curious about passing parameters by reference vs. and which is a better choice; then I was wondering if there is even a difference. So I did some testing and optimizations aside (I turned them all off), I wrote a small program that has 1 function that took some parameters by reference and I compiled it. I then changed the function to accept the parameters by pointer and compiled.
passing by reference
[source lang="cpp"]
int testing(int &a, int b);
int main(int argc, char *argv[])
{
int a = 0x66;
int b = testing(a, 0x10);
printf("%d %d", a, b);
return 0;
}
int testing(int &a, int b)
{
a = b + 0x0f;
return a + b;
}
[/source]
passing by pointer
[source lang="cpp"]
int testing(int *a, int b);
int main(int argc, char *argv[])
{
int a = 0x66;
int b = testing(&a, 0x10);
printf("%d %d", a, b);
return 0;
}
int testing(int *a, int b)
{
*a = b + 0x0f;
return *a + b;
}
[/source]
Assembly of by pointer AND by reference are listed here; EXACTLY the same!
[source lang="asm"]
push 10h ; b
lea eax, [ebp+a]
push eax ; a
call testing
ret
...
proc testing
push ebp
mov ebp, esp
mov eax, [ebp+b]
add eax, 0Fh
mov ecx, [ebp+a]
mov [ecx], eax
mov edx, [ebp+a]
mov eax, [edx]
add eax, [ebp+b]
pop ebp
endp
[/source]
I reverse engineered the 2 binaries and compared them, it appears to me that passing by reference and passing by pointer do the exact same thing... I'm talking EXACT, down to the same assembler instructions. Am I just crazy or are they indeed the same and choosing one over the other is simply aesthetics? Is there a benefit to one over the other?
passing by reference
[source lang="cpp"]
int testing(int &a, int b);
int main(int argc, char *argv[])
{
int a = 0x66;
int b = testing(a, 0x10);
printf("%d %d", a, b);
return 0;
}
int testing(int &a, int b)
{
a = b + 0x0f;
return a + b;
}
[/source]
passing by pointer
[source lang="cpp"]
int testing(int *a, int b);
int main(int argc, char *argv[])
{
int a = 0x66;
int b = testing(&a, 0x10);
printf("%d %d", a, b);
return 0;
}
int testing(int *a, int b)
{
*a = b + 0x0f;
return *a + b;
}
[/source]
Assembly of by pointer AND by reference are listed here; EXACTLY the same!
[source lang="asm"]
push 10h ; b
lea eax, [ebp+a]
push eax ; a
call testing
ret
...
proc testing
push ebp
mov ebp, esp
mov eax, [ebp+b]
add eax, 0Fh
mov ecx, [ebp+a]
mov [ecx], eax
mov edx, [ebp+a]
mov eax, [edx]
add eax, [ebp+b]
pop ebp
endp
[/source]
I reverse engineered the 2 binaries and compared them, it appears to me that passing by reference and passing by pointer do the exact same thing... I'm talking EXACT, down to the same assembler instructions. Am I just crazy or are they indeed the same and choosing one over the other is simply aesthetics? Is there a benefit to one over the other?