Darpangs
Darpangs

Reputation: 91

how can i declare variables via macros?

first of all, I'm using MS's Visual Studio and using C language.

Recently I need to declare variables with just one same statement which likes a macro.

However as you know, I can declare just one variable which have same name.

for example, this is not possible.

int iVar1;
int iVar1; // this is not possible. 

so I thought about macros include __LINE__ , if I can use this predefined macro, I can declare lots of variables via just one macro statement.

But it was difficult to make.

I made macro like this.

#define MY_LINE_VARIABLE        int g_iLine##__LINE__##Var = 0;

but after compile, i could get this variable named 'g_iLine_LINE_Var' instead of 'g_iLine123Var'

I want to know that is this possile, and how can i make it.

Furthermore, I need to use __FILE__ macro if possible. but this macro might be changed with string data. so I can not be sure.

Any advice will be helpful.

Thank you for your help in advance.

Upvotes: 7

Views: 21612

Answers (2)

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10375

From this link :

After the preprocessor expands a macro name, the macro's definition body is appended to the front of the remaining input, and the check for macro calls continues. Therefore, the macro body can contain calls to other macros.

So in your case :

MY_VARIABLE_LINE is converted to int g_iLine__LINE__Var;. But now __LINE__ is not a valid token anymore and is not treated as a predefined macro.

Aditya's code works like this:

MY_VARIABLE_LINE is converted to decl(__LINE__) which is converted to var(123) which is converted to int giLine123var = 0.

Edit: This is for GNU C

Upvotes: 6

A. K.
A. K.

Reputation: 38116

As @Chris Lutz has rightly said that, there might be a better way to accomplish what you want. Consider asking what you want to achieve.

But if you are just curious, this is the way to do:

#define var(z) int g_iLine##z##var = 0
#define decl(x) var(x)
#define MY_LINE_VARIABLE        decl(__LINE__)
MY_LINE_VARIABLE;
MY_LINE_VARIABLE;

Upvotes: 7

Related Questions