get the value of a c constant

C can't do this for you. You will need to store them in a different structure, or use a preprocessor to build the hundreds of if statements you would need. Something like Cogflect could help.


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.


A C preprocessor macro (that is, something named by a #define statement) ceases to exist after preprocessing completes. A program has no knowledge of the names of those macros, nor any way to refer back to them.

If you tell us what task you're trying to perform, we may be able to suggest an alternate approach.

Tags:

C++

C