#include <stdio.h>
#define VAL1 8
#define _CONCAT(name, v) name##v
#define CONCAT(name, v) _CONCAT(name, v)
void main()
{
int CONCAT(var, VAL1) = 5;
printf("%dn", var8);
}
I want to use macro concatenation with expression results. Compiles OK but the following does not compile:
#include <stdio.h>
#define VAL1 4
#define VAL2 2
#define _CONCAT(name, v) name##v
#define CONCAT(name, v) _CONCAT(name, v)
void main()
{
int CONCAT(var, VAL1 * VAL2) = 5;
printf("%dn", var8);
}
Tried in gcc and got an error.
Ofer Ebert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
The C preprocessor will not resolve C math operations in macro expansion.
Your first case compiles because int CONCAT(var, VAL1) = 5;
results in int var8 = 5
, which is valid.
In the second case, int CONCAT(var, VAL1 * VAL2) = 5
is expanded to int var4 * 2 = 5
, which doesn’t make sense.
VAL1 * VAL2
results in an integer constant expression so it is resolved at compile-time. However, compile-time does not necessarily mean during preprocessing. Preprocessing happens before the meaning of the resulting C code is evaluated by the compiler, so therefore you cannot use preprocessor tricks like ##
in this case.
In general it is a bad idea to create variable/function names from preprocessor macros.
4