Domanda

I'm running into the following problem when trying to use concatenation with the C preprocessor:

#define substitute(id) var##id
int main()
{
     int var0 = 999;
     int var1 = 998;
     int var2 = 997;
     int var3 = 996;
     int var4 = 995;

     int i = 0;

     for(i; i < 5; i++)
     {
          printf("Valor: %i \n",  substitute(i));      
     }

     system("PAUSE");
     return 0;

}

Is there a way for the preprocessor to be able to read the value on "i" instead of just concatenating "vari"?

È stato utile?

Soluzione

No. The preprocessor works before compilation and therefore before execution.

The define

#define substitute(id) var##id

will cause your loop to expand to:

 for(i; i < 5; i++)
 {
      printf("Valor: %i \n",  vari);      
 }

The preprocessor has no knowledge of the variable i, nor should it.

You should probably use an array:

int var[5] = {999,998,997,996,995};

and access it via []:

for(i; i < 5; i++)
{
    printf("Valor: %i \n",  var[i]);      
}

Altri suggerimenti

That's not possible at the pre-processor stage because what you want depends on values that are only known later, at runtime.

What you need is an array and the index operator, var[i].

You need to be aware that the macro is resolved once (by the preprocessor) before the file is compiled, so at runtime, each iteration in the loop will render the same result when "calling" substitute.

Nope, because the preprocessor runs at compile time, not runtime, but you can use an array:

int vars[] = { 999, 998, 997, 996, 995 };

for (int i = 0; i < 5; ++i)
    printf("Valor: %i \n", vars[i]);

No i is a runtime evaluation. There is no way for the preprocessor to know what the value of I could be.

Why would you do this with the preprocessor?

You seem to be trying to reinvent arrays:

int main() {
    int var[] = {999, 998, 997, 996, 995};
    int i;

    for (i=0; i<5; i++)
        printf("Valor: %i\n", var[i]);
    return 0;
}

As many said - no, macros doesn't know anything about what's going on in program compile-time or
run-time. But... if you wish you can generate some hackish code with macro which operates with stack directly (do not try this in home alone - it can blow your computer apart !! :-) )- define your macro as:

#define substitute(adr, max, id) *(adr + max - id)

and call like this:

printf("Valor: %i \n",  substitute(&var4,4,i));

But keep in mind that this is just for curiosity, in real life it is not recommended to play directly with stack, because compiler may (and usually will) re-order variable allocation on stack and also you will risk some nasty bugs to happen and etc... So better as others said - make some array and operate on that.

hth!

C macros are only expanded at compile time and your printf line would become

      printf("Valor: %i \n",  vari);      
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top