0

Im compiling using MSVC v141 with /std:c++17.

constexpr const char* test(const char* foo) {
    return foo + 1;
}

constexpr const char* bc = test("abc");

compiles just fine, whereas

constexpr const char* test(const char* foo) {
    constexpr auto bar = foo;
    return bar + 1;
}

constexpr const char* bc = test("abc");

Fails with:

error C2131: expression did not evaluate to a constant

failure was caused by a read of a variable outside its lifetime

note: see usage of 'foo'

Is this correct behaviour or a bug in MSVC?

Sebastian Hoffmann
  • 2,815
  • 1
  • 12
  • 22
  • I am trying to find if it is allowed to declare variables in a constexpr function. There are some limitations there. – Bart Feb 13 '20 at 13:05
  • 1
    Found the limitations listed: https://stackoverflow.com/questions/41618576/what-is-allowed-in-a-constexpr-function, – Bart Feb 13 '20 at 13:26

1 Answers1

5

Seems like expected behavior to me. A function declared with constexpr means that it can be evaluated at compile time but not that it is required to be. So your function should also be valid when evaluated at runtime. This is the problem line

constexpr auto bar = foo;

because it attempts to create a constexpr object from a non-constexpr one.

patatahooligan
  • 3,111
  • 1
  • 18
  • 27