Is it possible to swap two tokens with macros in C++

Viewed 34

Consider this C++ program:

#include <cstdio>

#define FOO BAR
#define BAR FOO

#define QUOTE(X) #X
#define EXPAND(X) QUOTE(X)

int main()
{
    printf("%s expands to %s\n", QUOTE(FOO), EXPAND(FOO));
    printf("%s expands to %s\n", QUOTE(BAR), EXPAND(BAR));
}

It outputs:

FOO expands to FOO
BAR expands to BAR

This is because FOO expands to BAR which expands to FOO which is not expanded again. And similarly for the second line.

Question: Is it possible to swap FOO and BAR with macros? I.e., is it possible to replace the two lines:

#define FOO BAR
#define BAR FOO

with something else so that the program will output:

FOO expands to BAR
BAR expands to FOO
1 Answers

I do not quite understand why you want to do this, or why you use macros in the first place. Hence, this may not fit your needs exactly:

#include <cstdio>

#define QUOTE(X) #X
#define REPLACE_FOO QUOTE(BAR)
#define REPLACE_BAR QUOTE(FOO)
#define EXPAND(X) REPLACE_##X

int main()
{
    printf("%s expands to %s\n", QUOTE(FOO), EXPAND(FOO));
    printf("%s expands to %s\n", QUOTE(BAR), EXPAND(BAR));
}

I am rather certain that there is a solution to your actual problem that does not rely on macros.

Related