Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Macros in C language cannot be expanding correctly

I wrote the following macro in C language:

#define STR(x) #x

I expect the following call to produce the result "11":

STR(5+6)

But the actual result it produces is "5+6"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I write macros to achieve the results I want? Is it possible to implement it in C or C++ language?

Thank you everyone!

>Solution :

Macros are text replacements done by the C Preprocessor; a tool that runs over your code before the compiler itself ever sees it, and consequently, before any compile-time constant expressions (such as 5+6) are evaluated. The preprocessor can do some arithmetic and comparisons to implement conditional compilation via the #if / #elif / #else directives, but no evaluation is performed in macro expansions outside of such conditional expressions (Thanks to @interjay for pointing this out).

Most importantly, the preprocessor has no notion of the language you’re writing in. It doesn’t know any of the syntax or semantics of either C or C++.

This is the main reason why in the C++ world, macros are generally considered "evil" (read: should be avoided unless absolutely necessary).
Note that the result you want here, parsing a compile-time-evaluated number into a compile-time-evaluated string, cannot be generally achieved even in the most recent C++ standard revision. constexpr strings do exist, but they do not survive long: See Is it possible to use std::string in a constant expression?

Bottom line: Can’t be done, you have to do it at runtime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading