umayneverknow
umayneverknow

Reputation: 190

Token pasting in c using a variable that increments

I have a set of arrays :msg1[] msg2[] .... msgn[] . And I need to use the values in a while loop. as msgi[]. When I define it as #define MSG(a) msg##a and put it in a loop and increment i, it expands it to msgi?

Upvotes: 0

Views: 1051

Answers (5)

Roee Gavirel
Roee Gavirel

Reputation: 19473

It can't be done cause macros are replaced at compilation time not runtime, so it will be replaced once...

what you could do is use 2D array if there are in the same size or use array of arrays if there are in different sizes:

//once in your code you need to do this:
int array0[];
int array1[];
//...
int arrayX[]; //X should be replaced with a real number...
int **arrayOfArrays = new (int*)[X+1];
arrayOfArrays[0] = array0;
arrayOfArrays[1] = array1;
//...
arrayOfArrays[X] = arrayX;

//now you could use it like that anytime in your code:
int i;
for(i = 0; i < X; ++i)
{
    //Do whatever you want to do, like:
    arrayOfArrays[i][0] = 1234;
}

Upvotes: 1

MOHAMED
MOHAMED

Reputation: 43608

build your c code with gcc -E myfile.c and you will see the reason

this called preprocessor code. the prprocessor code is the code generated by your compilator before the compilation. in this code the compilator replace the macros in your origin code with the content of the macro.

your origin code:

for (i=0; i<10; i++) {
    for (j=0; j<10; j++)
        MSG(i)[j] = 3;
}

preprocessr code generated from the origin code (could be seen with gcc -E):

for (i=0; i<10; i++) {
    for (j=0; j<10; j++)
        msgi[j] = 3;
}

You can use 2D array instead

int msg[5][5];

Upvotes: 1

John Colanduoni
John Colanduoni

Reputation: 1626

No, unfortunately it won't. C does not support runtime name lookups. Instead, you should use a two dimensional array of the form:

void** msg;

This will allow the arrays to be of different sizes and types, although you will have to cast to whatever type the array is.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409472

You can't do it that way. Instead you could create a new array, that contains pointers to the actual arrays:

int array1[...];
int array2[...];

int *all_arrays[] = { array1, array2 };

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249592

When I define it as #define MSG(a) msg##a and put it in a loop and increment i, it expands it to msgi?

No, it will not work that way, because the macro gets expanded before compilation, not after. You'll need a different approach, such as the 2D array suggested by @zakinster.

Upvotes: 0

Related Questions