Reputation: 751
I am trying to use C++17 if constexpr
feature but fail to compile a simple function.
Code:
template <auto B>
int foo()
{
if constexpr(B)
{
return 1;
}
else
{
return 2;
}
} // <- I get an error here
int main()
{
return foo<false>();
}
The error output by compiler:
<source>(12): error #1011: missing return statement at end of non-void function "foo<B>() [with B=false]"
}
Used -std=c++17 -O3 -Wall -Werror
compiler flags and icc 19.0.1
compiler.
Is this valid C++17 code? What is the reason behind this error?
Upvotes: 6
Views: 624
Reputation: 170173
Is this valid C++17 code?
Yes, it's valid. Exactly one return statement will be discarded, while the other will remain. Even if none remain, C++ still allows you to omit a return statement from a function. You get undefined behavior if the function's closing curly brace is reached, but that's a risk only if execution reaches that point.
In your case, execution cannot reach such a point, so UB is not possible.
What is the reason behind this error?
You used -Werror
, thus turning the compiler's false positive warning into a hard error. One workaround is to disable this warning around that particular function. This is purely a quality of implementation problem.
Upvotes: 6