I've been reading about stringification and token pasting and I was trying to access a variable using token pasting and modifying it's value. Is such a thing possible?
Suppose variables a0 and a1 are defined and at runtime I want to print their values using token pasting as printf("\n\rValue is %d",VAR_PARSER(0));
This is what I did.
#include "stdio.h"
#include "stdlib.h"
#define VAR_PARSER(dummyvar,index,value) do{\
dummyvar = index;\
a##dummyvar = value;\
}while(0);
unsigned char a0, a1, dummy;
int main (void)
{
unsigned char ucloopcnt;
for(ucloopcnt = 0; ucloopcnt < 2; ucloopcnt++) VAR_PARSER(dummy,ucloopcnt,(ucloopcnt * 10));
printf("\n\rValue is %d %d",a0,a1);
return 0;
}
Now, at this line a##dummyvar = value; I wanted an output as a0 = 10; and a1 = 20; respectively. But it seems that it translates to adummyand gives the following error adummy undeclared (first used in this funciton)
Can anyone suggest me how can I achieve it as I'm curious to solve this.
Your expectation that
a##dummyvarwould evaluate toa<value of dummyvar>fundamentally misunderstands what macros do (i.e. simple text substitution). The output ofadummyis correct.You cannot achieve dynamic access of variable values at runtime through macros, like you're trying to here, since they are evaluated before compilation and have no knowledge of a program's state at runtime.