0

I compile following code

int foo(int num) {
    int &numReference = num;
    int numVarible = num;
    return numVarible;
}

output assemble translation.

foo(int):
    push    rbp
    mov     rbp, rsp
    mov     DWORD PTR [rbp-20], edi
    lea     rax, [rbp-20]
    mov     QWORD PTR [rbp-8], rax
    mov     eax, DWORD PTR [rbp-20]
    mov     DWORD PTR [rbp-12], eax
    mov     eax, DWORD PTR [rbp-12]
    pop     rbp
    ret

int &numReference = num; output assemble:

    lea     rax, [rbp-20]
    mov     QWORD PTR [rbp-8], rax

int numVarible = num; output assemble:

    mov     eax, DWORD PTR [rbp-20]
    mov     DWORD PTR [rbp-12], eax

the question 1 is what's the difference about memeory comsumption.

When I change code from "return numVarible;" to "return numReference ;". assemble changes from

mov     eax, DWORD PTR [rbp-12]

to

mov     rax, QWORD PTR [rbp-8]
mov     eax, DWORD PTR [rax]

the question 2 is: when using reference, why assemble shows more line?

mariolu
  • 624
  • 8
  • 17
  • This question depends on your system. A reference can have 4 or 8 bytes. An `int` usually has the same size but it doesn't have to. The generated assembly code depends on your compiler and compiler options. Please describe your system, your compiler and your exact compile command. Enable compiler optimization and the generated assembly code will probably be the same in both cases: https://godbolt.org/z/bzaGb8EKT –  Mar 25 '21 at 08:48
  • I wouldn't bother looking at the assembly for this. Once you compile in release mode, a function like that will likely be optimized into nothingness anyway. In general a reference is the same as a pointer, so on a typical modern 64 bit home PC that will be 8 bytes but again it can vary for different machines. An int can also vary for different machines and compilers, but will typically take 4 bytes under say MS visual C++. –  Mar 25 '21 at 08:58

0 Answers0