条件预处理器比条件语句的优势 [英] Advantages of conditional-preprocessor over conditional statements

查看:79
本文介绍了条件预处理器比条件语句的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未与 #if #ifdef #ifndef #else #elif #endif

I have never worked with #if, #ifdef, #ifndef, #else, #elif and #endif.

在浏览某些源代码时,我发现这些指令被广泛使用。
对条件预处理器进行了一些阅读,但没有发现像它们与常规条件语句有何不同之类的线索。
因此,我想知道以下代码的优点是什么?

As I was going through some source-codes, I found an extensive use of these directives. Did some reading on conditional-preprocessors but found no clue like how are they different from normal conditional statements. So I was wondering what is the advantage of following code:

#include<iostream>
int main()
{
    int i = 0;

    #if i == 0
         std::cout<<"This";
    #else
         std::cout<<"That";
    #endif
    return 0;
}

在此之上:

#include<iostream>
int main()
{
    int i = 0;

    if (i == 0)
         std::cout<<"This";
    else
         std::cout<<"That";
    return 0;
}

此外,使用 /不-使用条件预处理器?

Also, when to-use/not-to-use conditional-preprocessor?

推荐答案

条件预处理器无法像您的第一个示例那样工作。

Conditional preprocessor doesn't work like in your first example.

它与常量一起工作,你知道吗?在编译时,它会查看各种条件并根据其放入/忽略源代码。

It's working with constants, you see? At compile time, it looks at the various conditions and puts in/omits source code according to it.

例如:

#define HAS_COMPARISON

int main() {
    #ifdef HAS_COMPARISON
        int i = 0;
        if(i == 0) std::cout << "This";
        else
    #else
        std::cout << "That";
    #endif
}

使用 define 设置,它将设置变量 i 并执行比较...总之,它将输出 This 。如果您注释该定义,则整个块将不在您的程序中,这意味着它将始终输出 That ,而无需设置变量或进行比较。

With the define set, it will set the variable i and perform the comparison...in short, it will output This. If you comment that define, the entire block will not be in your program which means that it will always output That, without ever setting the variable or doing the comparison.

这是预处理器定义的最常见用法。您还可以定义值并将它们与具有相同定义的变量行为进行比较,但这是另一个问题。

That's the most common use of preprocessor defines. You can also define values and compare those to have variable behaviour with the same define, but that's another issue.

一次:条件预处理器是在编译时评估的,变量条件在运行时评估。

Once more: Conditional preprocessor is evaluated at compile time, variable conditions are evaluated at runtime.

这篇关于条件预处理器比条件语句的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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