Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why unreachable code isn't an error in C++?

unreachable code is compile time error in languages like Java. But why it is just warning in C++ & C? Consider following example:

#include <iostream>
int f()
{ 
    int a=3;
    return a;
    int b=6;       // oops it is unreachable code
    std::cout<<b;  // program control never goes here
}
int main()
{
    std::cout<<f()<<'\n';
}

Shouldn't compiler throw an error in this program, because statements after return statements in function f() will never get executed? What is the reason for allowing unreachable code?

like image 784
Destructor Avatar asked May 26 '15 11:05

Destructor


1 Answers

Unreachable code is not a compile error in C++, but usually gives a warning, depending on your compiler and flags. If the compiler stopped when unreachable code is detected, then you would have less options for debugging code, because you would also have to manually remove code that is unnecessary.

A warning instead of an error makes sense. It's good that it's mentioned as one could have unintentionally left old code behind, but there is no reason not to compile anyway.

like image 118
bytecode77 Avatar answered Oct 14 '22 09:10

bytecode77