Reputation: 381
I need to generate some variable name with macro in C. It seems that # token-pasting operator does the job, but the result is always a string.
#define create_var( name ) char #name
will not work because name is expanding in "name" (as string).
#define create_var( name ) char prefix##name
will work, but all my vars will have a prefix.
Is there any trick available to obtain a simple name?
create(test)
to expand in
char test;
Thanks very much in advance,
Upvotes: 1
Views: 2217
Reputation: 5151
If you would like your variable name to appear unmodified (without prefix) in your preprocessed code, just use the formal parameter name of the macro, without #
and without ##
.
You can use #
in the macro definition if you want to convert some argument to a string constant. And you can use ##
to concatenate tokens to build new tokens (for example to build new variable names with prefixes and/or suffixes and other stuff). With out any of these the preprocessor will just insert the sequence of tokens passed to the macro unmodified (*).
(*): C preprocessor semantics are subtle. Preprocessor macros are replaced at multiple stages during macro expansion which can have quite unobvious results.
Upvotes: 3