2

In a macro I want to generate a variable with a different name and try to use __LINE__ as a way to differentiate them. A simplified sample:

#define UNIQUE_INT   int prefix##__LINE__

UNIQUE_INT;
UNIQUE_INT;

But it seems that __LINE__ is not expanding as I get "int prefix__LINE__' : redefinition" in the second one.

I suppose that __LINE__ can not be used in a macro definition as if it expanded would do to the line number of the #definition rather than the line of the invocation of the macro, but let me ask just in case someone has something to say.

3
  • This looks like a terrible idea. Even if you do manage to create variables with names based on line numbers, how do you intend to refer to these variables later on in your code? Commented Jan 29, 2016 at 15:19
  • 1
    @squeamishossifrage it's not a terrible idea, in general, it can be quite useful. the point is not that you will refer to a variable again, but rather that you want to ensure that it is constructed and not referred to in the rest of the function, because of some side-effect or debugging. For just int's like this I guess it's useless but probably its just an example. Commented Jan 29, 2016 at 15:20
  • Yes the sample is an oversimplification. As @chrisbeck says there's a good answer. Commented Jan 29, 2016 at 16:01

1 Answer 1

10

The problem is that in the preprocessor, the ## takes place before __LINE__ is expanded. If you add another layer of indirection, you can get the desired result.

For technical reasons you actually need two macros (sometimes if you use this in an existing macro you don't need the second one, it seems...):

#define TOKEN_PASTE(x, y) x##y
#define CAT(x,y) TOKEN_PASTE(x,y)
#define UNIQUE_INT \
  int CAT(prefix, __LINE__)

UNIQUE_INT;
UNIQUE_INT;
Sign up to request clarification or add additional context in comments.

3 Comments

But it doesn't work (gcc 4.9.2). It produces two lines of int prefix__LINE__;.
It does not work. neither in gcc or with Visual Studio. Same result.
Sorry, the first version had an error because I copied from my existing code a bit hastily. You need to use two macros, not just one. Actually the guy who posted this duplicate I guess made the same mistake at first: stackoverflow.com/questions/1597007/…... I should have checked for a duplicate before answering anyways.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.