65.9K
CodeProject is changing. Read more.
Home

Passing an empty parameter to a C macro

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jul 21, 2011

CPOL
viewsIcon

20848

How to fool the C pre-processor into accepting an empty parameter to a #define

Please see line marked "*** HERE ***". Tested in gcc 4.6.0.

#include <stdio.h>

#define nothing

#define RET_VAL_IF_NULL(p,v)   \
   if (p == NULL)              \
      return v;

#define RET_IF_NULL(p)         \
   RET_VAL_IF_NULL(p, nothing) /* *** HERE *** */

static void func1(char* ptr)
{
   RET_IF_NULL(ptr)
   printf("* %s from func1\n", ptr);
}

static int func2(char* ptr)
{
   RET_VAL_IF_NULL(ptr,1)
   printf("* %s from func2\n", ptr);
   return 0;
}

void main(void)
{
   char* p1 = 0, *p2 = "string";
   func1(p1);
   func1(p2);
   func2(p1);
   func2(p2);
}