Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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
like image 286
Dess Avatar asked Dec 21 '25 06:12

Dess


1 Answers

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.

like image 193
tkausl Avatar answered Dec 23 '25 20:12

tkausl