Redefining or changing macro value

扶醉桌前 提交于 2019-11-28 08:26:17

You can undefine it and define again:

#include <iostream>

#define AAA 13

int main()
{
    #undef AAA
    #define AAA 7
    std::cout << AAA;
}

outputs: 7

Please note that statements that start with # are preprocessor directives that are taken care of before the code is even compiled. In this case, this constant AAA will be simply replaced by 7, i.e. it works just like a textual replacement with no additional checks of syntax, no type safety etc...

...which is main reason why you should avoid using macros and #defines where they can be replaced by static functions and variables :)


Why "textual replacement" ?

Look at this code:

#include <iostream>

#define AAA 13

void purePrint() {
    std::cout << AAA;
}

void redefAndPrint() {
    #undef AAA
    #define AAA 7
    std::cout << AAA;
}

int main()
{
    #undef AAA
    #define AAA 4
    purePrint();
    redefAndPrint();
    purePrint();
}

preprocessor goes line by line from the top to the bottom, doing this:

  • ah, #define AAA 13, so when I hit AAA next time, I'll put there 13
  • look, purePrint uses AAA, I'm replacing it with 13
  • wait, now they tell me to use 7, so I'll stop using 13
  • so here in redefAndPrint() I'll put there 7

transforming the given code into this one:

#include <iostream>

void purePrint() {
    std::cout << 13;
}

void redefAndPrint() {
    std::cout << 7;
}

int main()
{
    purePrint();
    redefAndPrint();
    purePrint();
}

which will output 13713 and the latest #define AAA 4 won't be used at all.

Something like the following:

#undef HEIGHT_TESTS
#define HEIGHT_TESTS 17

// Use redefined macro

// Restore
#undef HEIGHT_TESTS
#define HEIGHT_TESTS 13

#define A 2

#define B (A+3)

#define C (B+4)

// I want here to change the value of A - possible?

#define A (C+6)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!