mercredi 22 février 2017

constexpr keywork doesn't affect on code generation

I wrote a simple program:

constexpr int strlen_c(char const* s)
{
    return *s ? 1 + strlen_c(s + 1) : 0;
}

int main()
{
    return strlen_c("hello world");
}

I expected that the compiler optimizes the function and evaluates its result in compile time. But actually the generated machine code evaluates the result in a loop:

    mov     edx, offset aHelloWorld ; "hello world"
loc_408D00:
    add     edx, 1
    mov     eax, edx
    sub     eax, offset aHelloWorld ; "hello world"
    cmp     byte ptr [edx], 0
    jnz     short loc_408D00
    leave
    retn

The program is being compiled with g++ version 5.3 with flags -std=c++11 -Ofast -O2. The same result I obtain in Visual Studio 2013, and g++ 4.9.

Quaestion what is the reason the compiler couldn't optimize the given code?

Aucun commentaire:

Enregistrer un commentaire