Is there a possibility to convert enumerator names to string in C?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One way, making the preprocessor do the work. It also ensures your enums and strings are in sync.
After the preprocessor gets done, you’ll have:
Then you could do something like:
If the use case is literally just printing the enum name, add the following macros:
Then do:
In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let’s say we want to use a #define with an enum:
The output would be:
This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.
See Stringification for more information.