igonejack
igonejack

Reputation: 2532

Why would someone define macros for first parameter including comma in C?

Inside ev.h of libev, I found some macros that seems weird that can't understand:

173 # define EV_P  struct ev_loop *loop /* a loop as sole parameter in a declaration */
174 # define EV_P_ EV_P,                /* a loop as first of multiple parameters */

The author defines a macro EV_P_ as EV_P, and use it as first parameter in function definitions like this:

int  ev_run (EV_P_ int flags EV_CPP (= 0));

Curious about why not just write EV_P, instead of EV_P_, so the function parameters would looks more clearly with a comma:

int  ev_run (EV_P, int flags EV_CPP (= 0));

Is this a trick in C or there are any other reasons? Not familiar with C, Google it before but still have no answers.

Upvotes: 4

Views: 235

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

One reason to do it this way would be to let you compile out the first parameter using preprocessor.

Imagine a situation when your code should be compiled against library X defining functions that take struct ev_loop *loop as their first parameter, or another library Y with functions that do not do that. In such case you could define a macro for EV_P_ that includes a comma for the library X, or conditionally define it to an empty string when compiling the code to run against library Y.

Upvotes: 2

Paul Hankin
Paul Hankin

Reputation: 58221

You can see why, if you look at more of the code.

#if EV_MULTIPLICITY
struct ev_loop;
# define EV_P  struct ev_loop *loop
# define EV_P_ EV_P,
...
#else
# define EV_P void
# define EV_P_
...
#endif

If EV_MULTIPLICITY is defined to be non-zero, then you get an extra argument to calls that include the EV_P_ macro at the start of the argument list. If it's not, then you don't.

If the macro didn't include the comma, there would be no way to drop this first argument.

Upvotes: 6

Related Questions