Is using a string constant in C++ ternary operator an invalid use of non-lvalue array?

Viewed 225

I have code which checks a condition using the ternary operator and then either returns a pointer to a c-string constant or throws an exception.

Strangely, the compilation only fails when I throw from one path of the ternary operator. If I put a string constant on both sides everything compiles.

// this line gives no compilation error
auto str = condition ? "foo" : "bar";

// this line gives "error: invalid use of non-lvalue array"
auto str = condition ? "foo" : throw std::runtime_error{"bad"};

This problem has started showing up in gcc 9.1. I have used lines with both of the above patterns for many years and they compile without warning in clang and earlier versions of gcc.

Is the above pattern actually invalid, or is this a compiler bug in gcc 9.1?

1 Answers

You are right. The ternary operator propagates the type and value category of one operand if the other is a throw-expression. The conditional-expression is an lvalue of type const char[4]. auto then deduces const char*. There is no "invalid use of non-lvalue array" here.

Also, the code compiles fine with clang. I'd say that this is a bug with GCC.

Related