1

Consider the following code:

struct S {};

#define CREATE_INSTANCE S instance_##__LINE__

int main()
{
    CREATE_INSTANCE;
    CREATE_INSTANCE;
    return 0;
}

What I want it to do is create two instances of S named instance_7 and instance_8. What it actually does is creates instance___LINE__ twice.

How to achieve what I want?

0

1 Answer 1

2

Using some indirection:

#define Concat_(a, b) a ## b
#define Concat(a, b) Concat_(a, b)
#define CREATE_INSTANCE S Concat(instance_, __LINE__)
Sign up to request clarification or add additional context in comments.

13 Comments

Interesting! Are you saying that macros are expanded in the context of other macro's arguments, but not in the context in which I used it here?
@VioletGiraffe Remember that the cpp is one pass actually.
And I still don't get why double indirection is required...
@user0042: but aren't macros supposed to be expanded in the expansion of other macros?
@Violet No, such things can't be actually solved without macros.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.