当我尝试在函数中应用#define 时出了问题

问题描述 投票:0回答:1

我尝试在条件语句中应用

#define
,但是,似乎出了问题。

    // The mode is forward by default
    #define FOR

    if ( mode == "forward")
    {
        clog << "mode == forward" << endl;
    }

    else if (mode == "reverse")
    {
        clog << "Enter reverse" << endl;

        #define REV
        #undef FOR
    }
    else 
    {
        cerr << "NOT A VALID MODE (FORWARD OR REVERSE)" << endl;
    }

    #ifdef FOR
    cout << "Switch to forward mode." << endl;
    #endif

    #ifdef REV
    cout << "Switch to reverse mode." << endl;
    #endif

输出是

mode == forward
Switch to reverse mode

这不是矛盾吗?

我觉得可能是编译的问题。 预编译后,代码如下所示

int main()
{
    string mode = "forward";
    if ( mode == "forward")
    {
        clog << "mode == forward" << endl;
    }

    else if (mode == "reverse")
    {
        clog << "Enter reverse" << endl;



    }
    else
    {
        cerr << "NOT A VALID MODE (FORWARD OR REVERSE)" << endl;
    }






    cout << "Switch to reverse mode." << endl;

}

我是 C++ 新手,谁能告诉我为什么会发生这种情况?

c++ c-preprocessor
1个回答
0
投票

预处理器指令在代码编译之前执行,并在非常基本的文本基础上进行操作,无需了解 C 结构。

此时您会到达:

    #ifdef FOR
    cout << "Switch to forward mode." << endl;
    #endif

    #ifdef REV
    cout << "Switch to reverse mode." << endl;
    #endif

FOR
已未定义,而
REV
已定义,因此预处理后的代码仅包含:

    cout << "Switch to reverse mode." << endl;
© www.soinside.com 2019 - 2024. All rights reserved.