Use local int to refer to constant defined as a macro

Viewed 60

I am self-taught C novice, and I am struggling to accomplish the following:

In my main() loop, I am incrementing an int "i". I have a separate header file where I have defined several macros that I would like to call in my main with "i".

For example, in my separate header file, I have the following constant:

#define _1 0x06

If I wanted to call _1 using i when i = 1, how do I convert i to _1 so that I can use it later; in this case, I want to assign the value of _1, which is 0x06 in my header file, to a specific index in a byte array, such as:

Array[3] = _1

Every time my loop iterates, I would like to have a different value assigned to the array index, such as:

Array[3] = _i

I hope that my question makes sense. Please pardon my lack of familiarity with technical programming verbiage.

1 Answers

This can not be done with the preprocessor, the value of the iterator is unknown at compile time, but you can use a lookup table:

int lookup[] = {0x00, 0x06, 0xab, ...};

Then, loop using the iterator as offset:

for (int i = 1; i < n; i++) x = lookup[i];

Related