编译器:如果条件总是真/假怎么办 [英] Compiler: What if condition is always true / false

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

问题描述

我想到了条件和编译器.我正在为 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 语句中的整个代码.类似地,如果条件始终为真,任何半体面的编译器都会跳过检查本身.

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天全站免登陆