Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put a preprocessor conditional inside a C macro?

Tags:

c

macros

Is there a way to write a C preprocessor macro that expands to different things depending on what argument it receives?

#define foo() ???

/* 1 */
foo(name)

/* 2 */
foo(_)

Desired result:

/* 1 */
int name;

/* 2 */
/*ignore*/

Yes, I know macros are evil. I'm asking this mostly out of curiosity.

like image 725
hugomg Avatar asked Sep 25 '13 17:09

hugomg


People also ask

What are conditional preprocessing macro?

In this tutorial, you will be introduced to c preprocessors, and you will learn to use #include, #define and conditional compilation with the help of examples. Working of C Preprocessor. The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled.

Can I #define in a macro?

(2) However, you cannot define a macro of a macro like #define INCLUDE #define STDH include <stdio. h> .

Can we define macro inside a macro?

No, because C 2011 [N1570] 6.10. 3.4 3 says, about macro replacement, “The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,…” Show activity on this post.

What are conditional macros?

A conditional macro definition is a line of the form: target-list := macro = value. which assigns the given value to the indicated macro while make is processing the target named target-list and its dependencies.


1 Answers

To expand on Gavin Smith's answer, you actually can check conditions within a macro expansion:

#define FOO_name 1
#define FOO__ 0

#define CONC(a,b) a##_##b

#define IF(c, t, e) CONC(IF, c)(t, e)
#define IF_0(t, e) e
#define IF_1(t, e) t

#define FOO(x) IF(CONC(FOO,x), int x;, )

FOO(name) // -> int name;
FOO(_)    // -> /*nothing*/

If you're feeling adventurous you can easily extend IF to allow commas, suppress macro expansion, etc. with helper macros.

As above though this does require that you know all of the desired names in advance.

like image 96
Leushenko Avatar answered Oct 11 '22 08:10

Leushenko