简体   繁体   English

为什么无法访问的代码在 C++ 中不是错误?

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

unreachable code is compile time error in languages like Java.无法访问的代码是 Java 等语言中的编译时错误。 But why it is just warning in C++ & C?但为什么它只是 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?编译器不应该在这个程序中抛出错误,因为函数 f() 中的 return 语句之后的语句永远不会被执行吗? What is the reason for allowing unreachable code?允许不可达代码的原因是什么?

Unreachable code is not a compile error in C++, but usually gives a warning, depending on your compiler and flags.无法访问的代码不是 C++ 中的编译错误,但通常会发出警告,具体取决于您的编译器和标志。 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.很高兴提到它,因为人们可能无意中将旧代码抛在了后面,但无论如何都没有理由不编译。

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 preprocessor defines (common cross platform developments, for example).代码是否可达取决于预处理器定义(例如常见的跨平台开发)。
  • 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此外,如果您希望这是一个错误,GCC 和 Clang 支持-Wunreachable-code ,因此您可以使用-Werror=unreachable-code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM