Click here to Skip to main content
15,891,513 members
Articles / Programming Languages / C
Tip/Trick

Passing an empty parameter to a C macro

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Jul 2011CPOL 20K   3
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
zvx
Software Developer
Brazil Brazil
I'm a long-time software developer living in Brazil.

I've been developing software for retail and banking automation in C/C++ for many years now. In the old days I even did some COBOL programming, and some assembly for the 8080.

My experience ranges from low level software such as interface code for serial devices for DOS and Windows (bar code scanners, printers, cash dispensers, etc) and goes to writing end user applications for POS terminals and bank ATMs. In between I've done a great deal of TCP/IP programming using the basic Berkeley sockets interface, which is my main interest nowadays.

Comments and Discussions

 
GeneralAh, I see. Its a C99 feature. Pin
Doc Lobster22-Jul-11 8:15
Doc Lobster22-Jul-11 8:15 
GeneralDoc Lobster: Yes, silly me, I didn't realize newer versions... Pin
zvx22-Jul-11 2:45
zvx22-Jul-11 2:45 
GeneralWhy don't you just leave the optional macro parameter empty?... Pin
Doc Lobster22-Jul-11 0:16
Doc Lobster22-Jul-11 0:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.