constexpr bug in clang but not in gcc?

c++, c++14, clang, constexpr

Solution

You compile your code in C++1y mode which contains wording to relax `constexpr` restrictions including all looping statements.

Have a look at N3652 which introduced these changes.

Problem

Let's take this simple example: ``` #include <iostream> namespace foo { constexpr int main(int argc, char* argv[]) { // code } } int main(int argc, char* argv[]) { return foo::main(argc, argv); } ``` Depend on what code is, clang will complain or no. If code is: ``` cout << "Hello!"; return 0; ``` clang complains: error: constexpr function never produces a constant expression [-Winvalid-constexpr] ``` constexpr int main(int argc, char* argv[]) { ``` note: non-constexpr function 'operator<< >' cannot be used in a constant expression ``` std::cout << "Hello!"; ``` /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/ostream:530:5: note: declared here ``` operator<<(basic_ostream<char, _Traits>& __out, const char* __s) ``` Fair enough, constexpr functions can't contain any cout statements, as we know. But what happens if we do this? ``` for (int i = 0; i < argc; i++) std::cout << argv[i]; ``` clang allows it! OK, but this can't possibly be a constexpr function even though it is marked constexpr, let's try to use it in constexpr context. ``` int arr[foo::main(argc, argv)]; ``` It works! So it must be clang bug? Reason I say clang because gcc complains: error: body of constexpr function 'constexpr int foo::main(int, char**)' not a return-statement So my conclusion is clang is wrong and gcc is right.

Original source