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?
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");
}