Reputation: 4953
This may seem silly but I seem to have forgotten the order of replacement of macros. Can someone help me figure out how to correctly swap the values of two macros? Consider the following:
#include <stdlib.h>
#include <stdio.h>
#define var1 5
#define var2 10
#define _VAL(a) a
#define VAL(a) _VAL(a)
int main(){
printf("var1 = %d, var2 = %d\n", var1, var2);
#define TEMP VAL(var1)
#undef var1
#define var1 VAL(var2)
#undef var2
#define var2 VAL(TEMP)
printf("var1 = %d, var2 = %d\n", var1, var2);
}
All I want is to have var1
to be replaced by 10 and var2
to be replaced by 5. Any ideas of how to fix this mess?
I'm trying to use this to try to figure something out for this other question:
C Macro to protect definitions
Upvotes: 0
Views: 175
Reputation: 16441
Can't be done.
As @jeffamaphone explains in his comment, macro definitions are not assignments.
#define A B
doesn't care about the value of B
. It just remembers that A
should be replaced to B
. Later, when A
is seen in the source, it's replaced to B
, which may then be replaced again, with whatever B
is defined to be at that time.
Upvotes: 2