Reputation: 3397
Given the following C++ code:
#include <cstdlib>
#include <iostream>
int main()
{
auto a = std::rand();
switch (a)
{
case 1: std::cout << "1\n"; break;
std::cout << "not 1\n";
}
std::cout << "done\n";
return 0;
}
I found something similar in some real code I was looking at. If my understanding of C++ is correct, in this case not 1
will never be printed.
Does anyone know of any reason when this could ever make sense? Why does the grammar even allow it? Why does no compiler I tried warn about the dead code, even when optimization is enabled?
Upvotes: 3
Views: 227
Reputation: 44268
Does anyone know of any reason when this could ever make sense?
It does not make any sense, just grammar allows it.
Why does the grammar even allow it?
Because it is extremely difficult and unnecessary task to prevent such cases on grammar level. Let's change your code a little bit:
switch( a ) {
case 1 : if( true ) break;
std::cout << "dead code here\n";
}
Do we want grammar to analize your code, detect and invalidate this? Definitely not. So in general it is not a task for grammar to prevent such cases at all. Syntax of C++ is already quite complicated and can be ambigious enough not to over complicate it to prevent this (which can be and should be done by code analyzer or compiler instead).
Why does no compiler I tried warn about the dead code, even when optimization is enabled?
This is completely different question and probably can be answered by compiler writers. For example here is the statement from gcc writers from mailing list:
The -Wunreachable-code has been removed, because it was unstable: it relied on the optimizer, and so different versions of gcc would warn about different code. The compiler still accepts and ignores the command line option so that existing Makefiles are not broken. In some future release the option will be removed entirely.
Upvotes: 1
Reputation: 24895
C/C++ design philosophy was that the programmer was an expert at, well, programming. If the programmer did something odd, it was assumed that they knew why.
So, as long as the code could be parsed and the program compiled, lots of nonsensical things are allowed.
We do not need to go as far as you go. This is legal and runs (https://onlinegdb.com/Piv4ddRYR)
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
printf("Goodbye World");
}
Upvotes: 9
Reputation: 1
In Switch case as the name suggests, you have to implement all the cases and separate each one with break statement, so to print "no 1" you have to have a case for it. This is the programming task that is implemented in optimization way, for example every line after "return". At the end the compiler has to compile everything, maybe we have "go to" statement :)
Upvotes: -4