为什么不可达的代码不是C ++中的错误? [英] Why unreachable code isn't an error in C++?

查看:304
本文介绍了为什么不可达的代码不是C ++中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法访问的代码是编译时错误在语言如Java。但为什么它只是在C ++& 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';
}

编译器不应该在这个程序中抛出一个错误,在函数f()将永远不会执行?允许无法访问的代码的原因是什么?

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?

推荐答案

无法访问的代码不是C ++中的编译错误,但通常会发出警告,具体取决于您的编译器和标志。如果编译器在检测到无法访问的代码时停止,则调试代码的选项会减少,因为您还必须手动删除不必要的代码。

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.

这篇关于为什么不可达的代码不是C ++中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆