编译器:如果条件始终为真/假,该怎么办 [英] Compiler: What if condition is always true / false

查看:193
本文介绍了编译器:如果条件始终为真/假,该怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我考虑条件和编译器.我正在为Arduino编写应用程序,因此我需要该应用程序尽可能快.

I think about conditionals and compilers. I am programming an application for Arduino and so I need the application to be as fast as possible.

在我的代码中,我有这个:

In my code I have this:

#define DEBUG false    

...

if (DEBUG)
{
  String pinName;
  pinName = "Pin ";
  pinName += pin;
  pinName += " initialized";
  Serial.println(pinName);
}

我想知道编译器是否在二进制文件中不包含代码(if块中的代码).条件始终为假,因此程序永远不会去那里.

I am wondering if the compiler does not include the code (code in if block) in binary file. The conditions is always false, so the program never goes there.

从另一侧看.如果DEBUG是正确的怎么办? Arduino是否测试条件或编译器仅在二进制文件中包含if的主体?

And from the other side. What if DEBUG is true? Does Arduino test the condition or the compiler include only the body of if in binary file?

我找到了此网站 https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_4.html 关于#if指令,因此我可以重写代码以使用这些指令,而不是"if".但是我想知道是否应该重写它,否则是否会浪费时间.

I found this site https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_4.html about #if directive, so I can rewrite the code to have these directives instead of "normal" if. But I would like to know if I should rewrite it or if it would be waste of time.

推荐答案

任何半正确的优化编译器都会在if语句中删除整个代码,前提是它可以在编译时告知条件始终为false.同样,如果条件始终为真,则任何体面的编译器都会跳过检查本身.

Any half-decent optimizing compiler will remove the whole code inside the if statement, if it can tell at compile-time that the condition always evaluates to false. Similarly, any half-decent compiler would skip the check itself if the condition is always true.

实际上,这完全等同于编译器开关",例如:

Indeed this is completely equivalent to "compiler switches" such as:

#define DEBUG


#ifdef DEBUG
...
#endif

首选使用带有#ifdef的编译器开关"语法,因为它使其他C程序员更清楚了其意图.但这只是编码风格的问题-它将产生与原始代码相同的二进制文件.

The "compiler switch" syntax with #ifdef is to prefer, as it makes the intent clearer to other C programmers. But that's just a matter of coding style - it will result in the same binary as your original code.

这篇关于编译器:如果条件始终为真/假,该怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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