Changing a macro at runtime in C

后端 未结 5 1432
野趣味
野趣味 2020-11-30 12:29

I have a macro defined. But I need to change this value at run time depending on a condition. How can I implement this?

5条回答
  •  自闭症患者
    2020-11-30 12:50

    You can't change the macro itself, i.e. what it expands to, but potentially you can change the value of an expression involving the macro. For a very silly example:

    #include 
    
    #define UNCHANGEABLE_VALUE 5
    #define CHANGEABLE_VALUE foo
    
    int foo = 5;
    
    int main() {
        printf("%d %d\n", UNCHANGEABLE_VALUE, CHANGEABLE_VALUE);
        CHANGEABLE_VALUE = 10;
        printf("%d %d\n", UNCHANGEABLE_VALUE, CHANGEABLE_VALUE);
    }
    

    So the answer to your question depends on what kind of effect you want your change to have on code that uses the macro.

    Of course 5 is a compile-time constant, while foo isn't, so this doesn't work if you planned to use CHANGEABLE_VALUE as a case label or whatever.

    Remember there are two (actually more) stages of translation of C source. In the first (of the two we care about), macros are expanded. Once all that is done, the program is "syntactically and semantically analyzed", as 5.1.1.2/2 puts it. These two steps are often referred to as "preprocessing" and "compilation" (although ambiguously, the entire process of translation is also often referred to as "compilation"). They may even be implemented by separate programs, with the "compiler" running the "preprocessor" as required, before doing anything else. So runtime is way, way too late to try to go back and change what a macro expands to.

提交回复
热议问题