1

Every time, I invoke the below C debug macro, I have to pass some argument. Else compilation fails.

#include <stdio.h>
#include <stdlib.h>

#define debug(fmt, ...)\
do{\
fprintf(stdout, "%s(%d) : " fmt, __FUNCTION__, __LINE__, __VA_ARGS__);\
}while(0)

int
main()
{
    debug("Debug 1");
}   

Here is the compilation error :

test.c:12:5: error: expected expression debug("Debug 1"); ^ test.c:6:70: note: expanded from macro 'debug' fprintf(stdout, "%s(%d) : " fmt, FUNCTION, LINE, VA_ARGS);\ ^ 1 error generated.

If I invoke the same macro with an argument :

debug("Debug 1 %s", "");

It compiles fine with no issues. Is is because of the compiler ? Does it work in latest compiler ?

Biffen
  • 6,249
  • 6
  • 28
  • 36
Anil Kumar K K
  • 1,395
  • 1
  • 16
  • 27
  • BTW please don't tag C questions as [tag:c++]. These are two different languages. – Lightness Races in Orbit Aug 24 '15 at 18:39
  • See [C `#define` macro for debug printing](http://stackoverflow.com/questions/1644868/c-define-macro-for-debug-printing/1644898#1644898) for a comprehensive discussion of debug printing macros. Note the sections on 'Single-argument variant' and 'GCC-specific technique' in particular. – Jonathan Leffler Aug 24 '15 at 18:43

1 Answers1

2

Variadic macros allow you to pass one or more arguments to a macro in one fell swoop. They do not allow you to pass zero arguments in its place.

Write a second macro that you can use if you do not wish to pass arguments.

[C99: 6.10.3/4]: If the identifier-list in the macro definition does not end with an ellipsis, the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition. Otherwise, there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...). There shall exist a ) preprocessing token that terminates the invocation.

If a different compiler (such as one of those distributed with Microsoft Visual Studio) allows you to pass zero arguments in place of ..., it is non-compliant. As you can read above, this rule is not implementation-dependant.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055