Programming in C

(Barry) #1
Debugging with the Preprocessor 393

You can define a macro that can take a variable number of arguments to produce your
debugging output:


#define DEBUG(fmt, ...) fprintf (stderr, fmt, __VA_ARGS__)


and use it instead of fprintfas follows:


DEBUG ("process (%i, %i)\n", i1, i2);


This gets evaluated as follows:


fprintf (stderr, "process (%i, %i)\n", i1, i2);


The DEBUGmacro can be used throughout a program, and the intent is quite clear, as
shown in Program 18.3.


Program 18.3 Defining a DEBUGMacro


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


#define DEBUG(fmt, ...) fprintf (stderr, fmt, __VA_ARGS__)


int process (int i1, int i2)
{
int val;


DEBUG ("process (%i, %i)\n", i1, i2);
val = i1 * i2;
DEBUG ("return %i\n", val);

return val;
}


int main (int argc, char *argv[])
{
int arg1 = 0, arg2 = 0;


if (argc > 1)
arg1 = atoi (argv[1]);
if (argc == 3)
arg2 = atoi (argv[2]);

DEBUG ("processed %i arguments\n", argc - 1);
DEBUG ("arg1 = %i, arg2 = %i\n", arg1, arg2);
printf ("%d\n", process (arg1, arg2));

return 0;
}

Free download pdf