Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why int& as function parameter uses QWORD(8 byte) memory but int parameter uses DWORD

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

references are usually implemented as pointers under the hood if it can’t be optimized away, and pointers are 8 bytes in 64-bit mode

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading