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

Allowed characters as macro parameters in C

I’m very sure this answer is a duplicate one, but I can’t find anything related, so… I have such a macro:

#define MACRO(x) #x

Is it allowed to do something like:

const char *var = MACRO(file.);

or

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

const char *var = MACRO(.ext);

or use both dots:

const char *var = MACRO(.field.);

GCC and clang do compile it and run it properly, but according to C standard which characters are allowed to be used in macro parameters. Are there characters that I can’t use for this or any ASCII character is allowed? And which paragraph of C standard says it?

>Solution :

In C, you can pretty much use any characters in macro parameters, including dots or other special characters. This is because when you use a macro, it just takes whatever you give it and uses it as is. The # in your macro is a special thing that turns your parameter into a string, but it doesn’t really care what the characters are.

The main rule from the C standard is that whatever you pass to the macro should be something that makes sense to the preprocessor. This means you can’t use stuff that would confuse it, like half of a comment or unmatched quotes. But regular characters, including special ones like dots, are totally fine.

So, for your examples with the dots, that’s all good and should work with any C compiler that follows the standard rules. The standard talks about this in the part about macros and how they replace stuff (it’s section 6.10.3 and its subsections, especially the bit about the # operator in 6.10.3.2).

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