Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is ## in c?

I have seen this snippet:

#define kthread_create(threadfn, data, namefmt, arg...) \
    kthread_create_on_node(threadfn, data, -1, namefmt, ##arg)
  1. what does ## stand for ?
  2. what is the meaning of ## when it appears out of a macro ?
like image 532
0x90 Avatar asked Aug 21 '12 10:08

0x90


1 Answers

Contrary to the other answers, this is actually GCC extension. When pasting variable args directly in, a problem occurs if no extra args were passed. Thus, GCC makes ## when used with __VA_ARGS__ or a varargs variable (declared with argname...). To paste if it contains a value, or remove the previous comma if not.

The documentation for this extension is here:

Second, the '##' token paste operator has a special meaning when placed between a comma and a variable argument. If you write

#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)

and the variable argument is left out when the eprintf macro is used, then the comma before the '##' will be deleted. This does not happen if you pass an empty argument, nor does it happen if the token preceding '##' is anything other than a comma.

eprintf ("success!\n")
      ==> fprintf(stderr, "success!\n");

The above explanation is ambiguous about the case where the only macro parameter is a variable arguments parameter, as it is meaningless to try to distinguish whether no argument at all is an empty argument or a missing argument. In this case the C99 standard is clear that the comma must remain, however the existing GCC extension used to swallow the comma. So CPP retains the comma when conforming to a specific C standard, and drops it otherwise.

like image 155
Richard J. Ross III Avatar answered Sep 29 '22 10:09

Richard J. Ross III