Let's say we have the following code in C (or similar language):
if (x < 10)
do_work1();
else if (x < 5)
do_work2();
Will the second branch of this conditional be executed in some cases? Will the compiler warn about unreachable code?
In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.
MISRA C defines unreachable code as code that cannot be executed, and it defines dead code as code that can be executed but has no effect on the functional behavior of the program.
Unreachable statements are statements that will not be executed during the program execution.
Unreachable Code Causes:The code that might be programmatically correct but won't be executed at any point of time due to the input data that is passed to the function.
Will the second branch of condition be executed in some case?
Shouldn't compiler warn about unreachable code?
Take this for example:
int x = 11;
void* change_x(){
while(1)
x = 3;
}
int main(void)
{
pthread_t cxt;
int y = 0;
pthread_create(&cxt, NULL, change_x, NULL);
while(1){
if(x < 10)
printf("x is less than ten!\n");
else if (x < 5){
printf("x is less than 5!\n");
exit(1);
}
else if(y == 0){ // The check for y is only in here so we don't kill
// ourselves reading "x is greater than 10" while waiting
// for the race condition
printf("x is greater than 10!\n");
y = 1;
}
x = 11;
}
return 0;
}
And the output:
mike@linux-4puc:~> ./a.out
x is greater than 10!
x is less than 5! <-- Look, we hit the "unreachable code"
do_work2
could be executed.do_work2
could be executed.It is not possible to prove in general whether or not code is reachable. The compiler can have some simple, understandable and fast-to-check rules that can detect simple cases of unreachable code. It should not include a slow and complex solving system that only sometimes works.
If you want extra checking then use an external tool.
The second branch will not be executed and the compiler shouldn't warn about unreachable code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With