Note that there are some explanatory texts on larger screens.

plurals
  1. POStandard alternative to GCC's ##__VA_ARGS__ trick?
    primarykey
    data
    text
    <p>There is a <a href="https://stackoverflow.com/questions/4054085/gcc-appending-to-va-args">well-known</a> <a href="http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html" rel="noreferrer">problem</a> with empty args for variadic macros in C99.</p> <p>example:</p> <pre><code>#define FOO(...) printf(__VA_ARGS__) #define BAR(fmt, ...) printf(fmt, __VA_ARGS__) FOO("this works fine"); BAR("this breaks!"); </code></pre> <p>The use of <code>BAR()</code> above is indeed incorrect according to the C99 standard, since it will expand to:</p> <pre><code>printf("this breaks!",); </code></pre> <p>Note the trailing comma - not workable.</p> <p>Some compilers (eg: Visual Studio 2010) will quietly get rid of that trailing comma for you. Other compilers (eg: GCC) support putting <code>##</code> in front of <code>__VA_ARGS__</code>, like so:</p> <pre><code>#define BAR(fmt, ...) printf(fmt, ##__VA_ARGS__) </code></pre> <p>But is there a standards-compliant way to get this behavior? Perhaps using multiple macros?</p> <p>Right now, the <code>##</code> version seems fairly well-supported (at least on my platforms), but I'd really rather use a standards-compliant solution.</p> <p>Pre-emptive: I know I could just write a small function. I'm trying to do this using macros.</p> <p><strong>Edit</strong>: Here is an example (though simple) of why I would want to use BAR():</p> <pre><code>#define BAR(fmt, ...) printf(fmt "\n", ##__VA_ARGS__) BAR("here is a log message"); BAR("here is a log message with a param: %d", 42); </code></pre> <p>This automatically adds a newline to my BAR() logging statements, assuming <code>fmt</code> is always a double-quoted C-string. It does NOT print the newline as a separate printf(), which is advantageous if the logging is line-buffered and coming from multiple sources asynchronously.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload