9

While experimenting with compile-time string manipulation, I've encountered a strange phenomenon:

#include <bit>

constexpr const char str[4] = "abc";

// error: constexpr variable 'x' must be initialized by a constant expression
constexpr auto x = std::bit_cast<int>("xyz");
// OK
constexpr auto y = std::bit_cast<int>(str);

See Compiler Explorer.

How come bit-casting is permitted for a char[] which is stored in a global variable, but not for string literals? std::bit_cast does not modify its source and the result is a value, so there is no potential of modifying the storage of string literals.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
  • 2
    Compiler bug. gcc accepts it [just fine](https://godbolt.org/z/K3x1s4P1b), and the only relevant rule around string literals is for passing them as template arguments which isn't happening here. – Barry May 09 '21 at 00:36
  • @Barry is `constexpr auto x = cast_string("xyz");` really ok? (I'm not implying, I actually don't know) – Ted Lyngmo May 09 '21 at 00:38
  • 1
    @TedLyngmo Yeah. None of the criteria [here](http://eel.is/c++draft/bit.cast#3) are violated. And `"xyz"` itself is a constant expression. – Barry May 09 '21 at 00:41
  • @Barry Thanks a bunch! OP got another vote from me there. – Ted Lyngmo May 09 '21 at 00:42
  • @Barry thanks, also for the code simplification. For some reason I was concerned about array-to-pointer decay, which is why I had the separate function. But it really doesn't apply here. The conclusion is to just use GCC then or is there some trivial workaround for clang? – Jan Schultke May 09 '21 at 00:44
  • 1
    "Reimplementing" [Ordinary multicharacter literal](https://en.cppreference.com/w/cpp/language/character_literal) as `'abc'` ^_^. – Jarod42 May 10 '21 at 09:38

0 Answers0