Changing a macro at runtime in C

Macros are replaced by the preprocessor by their value before your source file even compiles. There is no way you'd be able to change the value of the macro at runtime.

If you could explain a little more about the goal you are trying to accomplish undoubtedly there is another way of solving your problem that doesn't include macros.


You can't.

As a macro is resolved by the preprocessor before the compilation itself, its content is directly copied where you use it.

You can still use parameters to insert a conditional statement depending on what you want, or use a call-scope accessible variable.

If you want to change a single value, better use global scope variable, even if such behavior is discouraged. (as the intensive use of macro)


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 <stdio.h>

#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.


You can't. Macros are expanded by the Preprocessor, which happens even before the code is compiled. It is a purely textual replacement.

If you need to change something at runtime, just replace your macro with a real function call.