0

I'm using Visual Studio 2013 + CTP.

I have defined the following function:

constexpr DWORD const_getHash(const char *str, DWORD curHash = 0) {
    return !*str ? curHash : const_getHash(str + 1, 
        (curHash >> 13 | curHash << (32 - 13)) + (*str >= 'a' ? *str - 32 : *str));
}

which I use like this:

DWORD hash = const_getHash("ok");

The compiler doesn't issue any warnings but by looking at the "disassembly" I can tell that const_getHash() is executed at runtime.

What's wrong?

edit: If I force the function to be executed at compile-time with

constexpr DWORD hash = const_getHash("ok");

the compiler says

Error   1   error C2127: 'hash': illegal initialization of 'constexpr' entity with a non-constant expression
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Kiuhnm
  • 478
  • 3
  • 13
  • It's probably some limitation of the VS compiler, since it works on [GCC](http://coliru.stacked-crooked.com/a/7355eb8392a93539) – Tom Knapen Mar 02 '15 at 13:05
  • @TomKnapen Damn! I might turn to GCC then. I can't compute the hashes at runtime because I'm writing a shellcode which needs to be as small as possible. – Kiuhnm Mar 02 '15 at 16:01

1 Answers1

0

constexpr doesn't force the function to be executed at compile-time. It just tells the compiler that the function can be executed at compile-time if needed.

constexpr functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well.

(Quoted from the accepted answer here.)

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157