For this code:
enum class Colors { Red, Green, Blue };
int fun(Colors color)
{
switch (color)
{
case Colors::Red: return 0;
case Colors::Blue: return 1;
case Colors::Green: return 2;
}
}
My compiler threw this error at me:
warning: control reaches end of non-void function [-Wreturn-type]
I know it is undefined behavior to have no return statement in a function, but is it undefined behavior to not have a return statement for all control paths? Thanks in advance.
g++
gurns about this, but interestingly,clang++
does not. IMHO there should always be an option for users who use their own functions properly and have no interest in being warned that some imaginary caller could cast an out-of-range value into anenum class
and pass it in. Assuming properenum class
usage, thisswitch
will always hit a validcase
, and the end of the function won't be flowed off, meaning no UB is involved. Why doesg++
insist that I must artificially insert adefault:
orreturn
orabort()
just to avoid being shouted at about this?enum
(including non-class
) cases, is silent, and if you don't - of course you get theWswitch
message, but thenwarning: control may reach end of non-void function [-Wreturn-type]
. So Clang'sWreturn-type
only fires in missing cases and even then says "may reach" (i.e. thanks to a stupid/malicious caller), not reaches. GCC could do one better by defaulting to warning about such callers - but allowing the warning to be disabled by competent ones. But it seems they don't want to be that nuanced ;-) gcc.gnu.org/bugzilla/show_bug.cgi?id=53479