Quick Q: Can computing the length of a C string really be compile-time constexpr? -- StackOverflow

Quick A: Yes, when the string being traversed is itself a constant expression, such as a string literal.

Recently on StackOverflow:

Computing length of a C string at compile time. Is this really a constexpr?

I'm trying to compute the length of a string literal at compile time. To do so I'm using following code:

#include <cstdio>

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

int main()
{
    printf("%d %d", length("abcd"), length("abcdefgh"));
}

Everything works as expected, the program prints 4 and 8. The assembly code generated by clang shows that the results are computed at compile time:

0x100000f5e:  leaq   0x35(%rip), %rdi          ; "%d %d"
0x100000f65:  movl   $0x4, %esi
0x100000f6a:  movl   $0x8, %edx
0x100000f6f:  xorl   %eax, %eax
0x100000f71:  callq  0x100000f7a               ; symbol stub for: printf

My question: is it guaranteed by the standard that length function will be evaluated compile time?

If this is true the door for compile time string literals computations just opened for me... for example I can compute hashes at compile time and many more...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.