In an embedded system define:
#define Row1_PORT GPIOD
#define Row1_PIN GPIO_PIN_4
#define Row2_PORT GPIOD
#define Row2_PIN GPIO_PIN_7
#define Row3_PORT GPIOD
#define Row3_PIN GPIO_PIN_1
#define Row4_PORT GPIOD
#define Row4_PIN GPIO_PIN_3
//------------
#define Paste2(a,b) a ## b
#define Paste(a,b) Paste2(a,b)
#define NRows 4
I want use above defined macros in a loop like this:
for(i=1;i<=NRows;i++)
{
GPIO_Init(Paste(Paste(Row,i),_PORT),Paste(Paste(Row,i),_PIN),GPIO_MODE_IN_PU_NO_IT);
}
instead of
GPIO_Init(Row1_PORT,Row1_PIN);
GPIO_Init(Row2_PORT,Row2_PIN);
GPIO_Init(Row3_PORT,Row3_PIN);
GPIO_Init(Row4_PORT,Row4_PIN);
Is it possible?
I need some things like __COUNTER__
in ANSI C or C++. My compiler is IAR.
The preprocessor runs at compile time and textually modifies the source code presented to the compiler. What you are seeking to do is not possible; the compiler would embed the letter i
into the macro expansions, not the value of the variable i
at run-time.
I would probably use something like:
static const int ports[] = { 0, Row1_PORT, Row2_PORT, Row3_PORT, Row4_PORT };
static const int pins[] = { 0, Row1_PIN, Row2_PIN, Row3_PIN, Row4_PIN };
for (int i = 1; i <= NRows; i++)
GPIO_Init(ports[i], pins[i]);
Or I'd write it out longhand (as you show in your 'instead of' option) — there is little penalty and possibly a small saving for just 4 entries. If you have 100 ports to initialize, the loop would be better, of course.
Also, if you're going to use the port and pin numbers again in future (in other portions of the code than just the initialization code), having the arrays available will allow for greater flexibility.