简体   繁体   English

gcc / g ++是否生成if(false)语句的主体?

[英]Does gcc/g++ generate the body of an if(false) statement?

In C++, imagine I have a function like 在C ++中,假设我有一个像

bool Aclass::func(){
   return true;
}

which is called in the main in this way 这种方式主要被称为

 if(!func()) { 
    //do stuff 
 }

Does the compiler generate these lines of code? 编译器会生成这些代码行吗?

Like all optimization questions, it depends on the compiler and the flags given. 像所有优化问题一样,它取决于编译器和给定的标志。 Having said that, a decent modern compiler will be able to remove dead code like this if optimizations flags are provided. 话虽如此,如果提供了优化标志,那么不错的现代编译器将能够像这样删除死代码。 Try https://godbolt.org/ to see for yourself which compiler and which flags will succeed in removing the dead code. 尝试https://godbolt.org/自己查看哪个编译器和哪个标志将成功删除无效代码。

The compiler at compilation step will treat those lines of code as valid. 编译器将在编译步骤将那些代码行视为有效。 For example, if you have an error in those lines of code then it will be flagged by the compiler. 例如,如果您在这些代码行中有错误,则编译器将对其进行标记。 So for example, the following will not compile 因此,例如,以下内容将无法编译

if (false) {
    auto s = std::string{1.0};
}

But most optimizers will not add that code in the compiled form for that source file. 但是大多数优化器不会以该源文件的编译形式添加该代码。 However related code is still added if needed, for example 但是,如果需要,仍会添加相关代码,例如

if (true) { ... } 
else { ... }

here the else code for the else statement will essentially be converted to 在这里,else语句的else代码将基本上转换为

{
   ...
} 

when the code gets converted to its compiled form. 当代码转换为编译形式时。


@Yakk brings up a great point . @Yakk提出了一个观点 The compiler not including such code is called dead code elimination . 不包含此类代码的编译器称为无效代码消除 However labels can still be used to reach the body code. 但是,标签仍然可以用于到达正文代码。


Also note that in these situations where an expression is evaluated at compile time. 另请注意,在这些情况下,在编译时对表达式求值。 Then you can use a new construct from C++17 known as if constexpr . 然后,您可以使用C ++ 17中的新构造,即if constexpr However as I mentioned with compiler errors persisting even in dead code in runtime if s the situation is different for if constexpr s, for more read the code examples here http://en.cppreference.com/w/cpp/language/if#Constexpr_If and this answer https://stackoverflow.com/a/38317834/5501675 但是,正如我提到的那样,即使在运行时死代码中, if s仍然存在编译器错误, if constexpr的情况就不同,有关更多信息,请参见此处的代码示例http://en.cppreference.com/w/cpp/language/if# Constexpr_If和此答案https://stackoverflow.com/a/38317834/5501675

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

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