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

拥有回忆 提交于 2019-12-09 20:50:39

问题


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?


回答1:


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.




回答2:


Unreachable code is a warning because there is no need for it to be an error, further, it can't always be easily avoided.

  • Code expanded from macros or that check constants may result in unreachable code.
  • Code may reachable or not depending on the pre-processor defines
    (common cross platform development for eg).
  • Generated code may result in unreachable code that isn't practical to detect in the generation phase.

Further, if you want this to be an error, GCC and CLANG support -Wunreachable-code, so you can use -Werror=unreachable-code



来源:https://stackoverflow.com/questions/30457156/why-unreachable-code-isnt-an-error-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!