In the code below,
int firstFunction(int& refParam)
{
std::cout << "Type of refParam is: " << typeid(refParam).name() << '\n';
return refParam;
}
int secondFunction(int param)
{
std::cout << "Type of param is: " << typeid(param).name() << '\n';
return param;
}
int main()
{
int firstVar{ 1 };
int secondVar{ firstFunction(firstVar) };
int thirdVar{ secondFunction(firstVar) };
}
Console output is
int
int
When i check the assembly code in Godbolt link.
firstFunction(int&):
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
mov eax, DWORD PTR [rax]
pop rbp
ret
secondFunction(int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov eax, DWORD PTR [rbp-4]
pop rbp
ret
reference parameter creates a space of 8 bytes QWORD PTR [rbp-8], rdi
instead of 4 bytes in second function DWORD PTR [rbp-4], edi
After seeing eax, DWORD PTR [rax]
in line 6 in firstFunction(int&):
I thought it might be because the first half(eax) stores the value adress but when i create a third function have char& as parameter it also creates 8 byte space. Godbolt Link
Is there any reason for that?