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

Macro that expands to value or empty, based on boolean argument

I’m generating some compile-time code. I need to append a suffix to a generated function name, based on a macro boolean. The suffix is either present or empty. How to do that?

#define FUNC_NAME(name, hasSuffix) name ## MAYBE_SHOW_SUFFIX(hasSuffix)

FUNC_NAME(foo, true);  // would generate: foo_
FUNC_NAME(foo, false); // would generate: foo

>Solution :

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

Use the fact that the result of a macro expansion is expanded again:

#define WITHSUFFIX_true(name) name ## _
#define WITHSUFFIX_false(name) name

#define FUNC_NAME(name, hasSuffix) WITHSUFFIX_ ## hasSuffix(name)

FUNC_NAME(foo, true);  // would generate: foo_
FUNC_NAME(foo, false); // would generate: foo

Result

foo_;
foo;

https://godbolt.org/z/EEM938jx9

Note that this only works because it expands the macro WITHSUFFIX_true or WITHSUFFIX_false given the condition true or false exactly. It won’t work for other values like 1 or !0 or similar.

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