cc-preprocessor

Get the value of a C constant by name


I have a .h file in which hundreds of constants are defined as macros:

#define C_CONST_NAME Value

I need a function that can dynamically get the value of one of these constants.

Needed function header:

int getConstValue(char * constName);

Is that even possible in the C language?


Solution

  • Here you go. You will need to add a line for each new constant, but it should give you an idea about how macros work:

    #include <stdio.h>
    
    #define C_TEN 10
    #define C_TWENTY 20
    #define C_THIRTY 30
    
    #define IFCONST(charstar, define) if(strcmp((charstar), #define) == 0) { \
        return (define); \
    }
    
    int getConstValue(const char* constName)
    {
        IFCONST(constName, C_TEN);
        IFCONST(constName, C_TWENTY);
        IFCONST(constName, C_THIRTY);
    
        // No match                                                                                                                                                                                                                              
        return -1;
    }
    
    int main(int argc, char **argv)
    {
        printf("C_TEN is %d\n", getConstValue("C_TEN"));
    
        return 0;
    }
    

    I suggest you run gcc -E filename.c to see what gcc does with this code.