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?
gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.
If the C++ compiler provides its own versions of the C headers, the versions of those headers used by the C compiler must be compatible. Oracle Developer Studio C and C++ compilers use compatible headers, and use the same C runtime library. They are fully compatible.
Due to this, development tools for the two languages (such as IDEs and compilers) are often integrated into a single product, with the programmer able to specify C or C++ as their source language. However, C is not a subset of C++, and nontrivial C programs will not compile as C++ code without modification.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With