Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringification on a enumeration member

Tags:

c

macros

I need to convert an enumeration member (its value, not the identifier) to a string. I have tried the following, which works for a MACRO (TYPE_A), but not for an enum value (typeA). This is a little bit strange in my opinion.

Do you have any idea how to do this?


#define _tostr(a) #a
#define tostr(a) _tostr(a)

typedef enum _SPECIAL_FOLDER_ID {
    typeA = 3,
    typeB = 4,
} SPECIAL_FOLDER_ID;

#define TYPE_A 3

int main() {
    //this is working, but the information is a macro (TYPE_A)
    printf("The string is " tostr(TYPE_A) ".\n");

    //this is not working for typeA (defined in an enumeration)
    printf("The string is " tostr(typeA) ".\n");
    return 0;
}


The output is:

The string is 3.
The string is typeA.

I need to modify the code in some way so that the second line of the output will be "The string is 3."

Thanks!

PS: I do not want to print the value using printf. I need a static string containing that value. I only use printf to test the result...

like image 661
botismarius Avatar asked Dec 08 '25 08:12

botismarius


2 Answers

The preprocessor does not know C. It simply knows "text".
When it processes your file, typeA is just 5 letters. Only the compiler will know (after the preprocessor is done) that typeA has a value, and that the value is 3.

like image 84
pmg Avatar answered Dec 10 '25 00:12

pmg


There's not really a good way to accomplish this. The best I could come up with is

#define typeA_ 3
#define typeB_ 4

enum
{
    typeA = typeA_,
    typeB = typeB_
};

#define tostr__(E) #E
#define tostr_(E) tostr__(E)
#define tostr(E) tostr_(E ## _)
like image 41
Christoph Avatar answered Dec 10 '25 00:12

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!