3 ms·
>> True, but a compiler will detect unreachable code when you do Interestingly, neither clang nor g++ give a warning for this case: int main(int argc, char
by w0utert 7y ago
>> True, but a compiler will detect unreachable code when you do
Interestingly, neither clang nor g++ give a warning for this case:
int main(int argc, char **argv)
{
int x = argc;
if (x == 0)
{
x = 10;
}
else if (x == 1)
{
x = 20;
}
else if (x == 0)
{
x = 30;
}
return 0;
}
# g++ bla.cpp -o out -Wall
(no warning)
# clang bla.cpp -o out -Wall
(no warning)
I assume this is because the compiler can never be 100% sure a variable cannot be changed midway through testing each of the conditions because of aliasing, so it won't throw a warning. In this particular example this obviously is not relevant, but I can imagine some pathological example where one of the tests has side effects that change the result of the later tests, and to avoid false positives the compiler simply never warns about unreachable code for these things.
In a sense, this is exactly what I mean by writing code that matches exactly what you want to happen. If I write 'switch (x)', it's pretty clear the test is executed exactly once. If I write a sequence of if-elseif-elseif-else statements, the conditions are evaluated in sequence, which is not what I want.