From Newsgroup: comp.std.c
On 2/7/21 12:30 PM, emanuele cannizzo wrote:
In my code I have a lot of vectors with a similar name:
vector1, vector2, vector3, vector4, ...
Because I don't want to write the same code with the only difference of the names of vectors I tried creating this macro:
#define VECTOR(x) vector##x
I tried this code as an example:
int n = 1;
printf("%d", VECTOR(n)[0]);
I thought that was the same as printf("%d", vector1[0]); but the compiler substitutes the macro VECTOR(n)[0] with vectorn[0]
Can you give me a solution to this problem or suggest me other tecniques to use? Thanks
The problem is that macro substitution occurs at compile time
(specifically, during translation phase 4), and it is purely textual.
As far as the preprocessor is concerned, "n" is just a character string,
which is why the result of the macro expansion is "vectorn". "n" doesn't
become the name of a variable with a value until translation phase 7,
and it doesn't become the variable itself (as opposed to the name of a variable) until run time.
There's several alternatives you could use, one of which is
int *vector[] = {vector0, vector1, vector2, vector3};
and then
vector[n][0].
--- Synchronet 3.18c-Linux NewsLink 1.113