When I compile the following code at c++11 standard, it works fine with clang, and also with gcc, but gcc (all versions that I tested 4.8.2, 4.9.2, 5.1.0) gives a warning:
#include <iostream>
enum class FOO { A, B, C };
const char * bar(FOO f) {
switch (f) {
case FOO::A:
return "A";
case FOO::B:
return "B";
case FOO::C:
return "C";
}
}
int main() {
unsigned int x;
std::cin >> x;
FOO f = static_cast<FOO>(x % 3);
std::cout << bar(f) << std::endl;
}
The warning is -Wreturn-type
:
main.cpp: In function ‘const char* bar(FOO)’:
main.cpp:14:1: error: control reaches end of non-void function [-Werror=return-type]
}
^
cc1plus: all warnings being treated as errors
I still get the warning even with -O2
or -O3
optimizations -- does this mean that even at high optimization levels, gcc cannot dead-code eliminate the 'end' of the function?
Notably, it doesn't give me the warning about unhandled switch cases.
Edit: From experiments with godbolt, it appears that even at high levels, it doesn't dead code eliminate that. I'm not sure whether it could or if clang does for instance.
Is there a good way to suppress this warning locally within such a function, or is the only way to suppress this to disable the warning generally?
Edit: I guess the question poses a natural language lawyer question, judging from the answers:
Can a conforming compiler dead-code eliminate the "end" of the
bar
function in my listing? (Or 101010's version withreturn nullptr;
appended?) Or does conforming to the standard require that it generate code to handle enum values that aren't part of the enum definition?
My belief was that it could dead-code eliminate that but you are welcome to prove me wrong.