samedi 20 avril 2019

constexpr vs inline assembly code difference

I came across this awesome online editor https://godbolt.org/ which shows assembly version of your code. I was also reading about new C++ 11 features and found out about constexpr.

take a look at square function below :

constexpr int square(int num) {
    return num * num;
}

int main()
{
    int result = square(2);
    return 0;
}

and following assembly code generated for two versions (constexpr and inline)

CONSTEXPR

main:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 4
        mov     eax, 0
        pop     rbp
        ret

INLINE

square(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     eax, DWORD PTR [rbp-4]
        imul    eax, DWORD PTR [rbp-4]
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     edi, 2
        call    square(int)
        mov     DWORD PTR [rbp-4], eax
        mov     eax, 0
        leave
        ret

I read everywhere that functions like this can be inlined but why there's a function call code in asm version? According to inline definition it should be avoided right?

Aucun commentaire:

Enregistrer un commentaire