#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.