Search code examples
ansi-c

Ansi C how to dinamically call a CONSTANT


How can I dinamically call the right constant defined here as:

#define MyCONSTANT_00 "STATICVALUE"
#define MyCONSTANT_01 "STATICVALUE1"
#define MyCONSTANT_02 "STATICVALUE3"

for (Index = 0; Index < record; Index++) 
{
    myfunction(MyCONSTANT_+Index);
}

This return an error while compiling:

Undefined identifier MyCONSTANT_

If I call the function direclty with the constant it works fine:

  myfunction(MyCONSTANT_00);

Solution

  • You can't:

    #define and corresponding replacements are handled by the pre-processor whereas the for loop (and the Index irterator) is handled by the compiler.

    There is no looping mechanisms in the pre-processor.

    I would suggest to define a static constant array and iterate through it in loop:

    const char* const MyCONSTANT[] = {"STATICVALUE", "STATICVALUE1", "STATICVALUE3" }
    
    for (Index = 0; Index < record; Index++) 
    {
        myfunction(MyCONSTANT[Index]);
    }