简体   繁体   中英

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 ?

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 };

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];

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;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM