Search code examples
cmacrosc-preprocessorvariadicvariadic-macros

Macro for printing variadic arguments, with the option of no arguments


I want to implement the following macro:

ASSERT(condition, ...)          

Which is defined like this:
1. If it gets only one parameter - if the condition is false we just print "condition is false".
2. If it gets two parameters or more - same as above, and in addition: the second argument will be printing format (similar to printf format) and the rest of the arguments will be for the printing format (again, just like printf). So in addition to the possible print of "condition is false" it will also print the format like printf does.

Examples:

  1. ASSERT(0) :

    condition is false 
    
  2. ASSERT(1) :

    (empty output)
    
  3. ASSERT(0, "hi") :

    condition is false
    hi
    
  4. ASSERT(0, "number seven: %d", 7) :

    condition is false
    number seven: 7
    

My problem here is that I don't know how to support the case of zero variadic arguments. If I knew I would get for sure at least two parameters - I could implement it like in the code below but it isn't the case.
How can I modify the code below for supporting what I need?

#define ASSERT(condition, format,...) do { \
  if (!(condition)) { \
    printf(format, ##__VA_ARGS__); \
  } \
} while (0)

Solution

  • You can remove format argument from this macro (pull them into variadic part). "condition is false\n" and format string (if present) will be concatenated into one string without ##.

    #include <stdio.h>
    
    #define ASSERT(condition, ...) do { \
      if (!(condition)) { \
        printf("condition is false\n" __VA_ARGS__); \
      } \
    } while (0)
    
    int main()
    {
        ASSERT(1);
        ASSERT(0);
        ASSERT(0,"Hi\n");
        ASSERT(0,"number is %d\n",7);
        return 0;
    }
    

    Limitation:

    • format should be only string literal, not pointer to character array