How To: Use C Macros Efficiently in Your Code

Earlier I wrote about using C debugging macros when designing and unit testing your code. This how-to will outline other uses of C Macros.

1. Using C Macros for the so-called Magic Number

One great way of taking advantage of the C Preprocessor is to use Macros for any numbers in your code that you may want to change in the future, and is referenced multiple times in your code. This saves time because if that variable value needs to be changed, it can be done in only one place. For instance:

#define MAX_PACKET_SIZE 65535

Thus if you were allocating a buffer size, you only need to modify that value. Macros are also usually defined at the top of your code (it must be defined at an earlier line than when you plan to reference it, unless you have it defined in your header file).

So if you had something like this as a ridiculous example:

data_buffer[MAX_PACKET_SIZE];
 
for(i = 0; i < MAX_PACKET_SIZE; i++){
    fprintf(stderr, "%u\n", MAX_PACKET_SIZE);
}

You now have to only modify the #define set earlier and the preprocessor will replace every reference to MAX_PACKET_SIZE with that value.

2. Using C Macros for Basic Functions

Lets say you knew you needed to a lot of multiplication in your program.

#define MULT(x,y) (x) * (y)

Now you can call MULT(5,6) which will spit out 30.

3. C Macro to Comment Out Code

Another very handy use of C macros is when commenting out code. If you have already commented out a block of code using /* … */ then within that block you have another set of /* … */ and perhaps a few //. You can actually just do:

#if 0
/* comment ...
*/
 
// code
 
/* comment */
#endif

This will actually remove all code during compilation that exists between your definitions.

4. Using C Macros to Compile for Target Architecture(s)

Sometimes you may need to compile a certain block of code if running on a Win32 machine versus a Unix based environment. For example:

#ifdef WIN32
  print(stdout, "Hello\n");
#else
  fprintf(stderr, "Yay Linux Machine\n");
#endif

This way you can pass in -DWIN32 to gcc to compile your program for a Windows machine.

5. Using a C Macro to Swap Two Variables

A very handy swap function can also be written in Macro form that will swap the values of two variables. This can become handy if implementing a various sorting algorithms where values must be swapped.

/*
 * Swaps two values.
 * Requires tmp variable to be defined.
 */
#define SWAP(x, y) \
  do { \
    tmp = x; \
    x = y; \
    y = tmp; } \
  while (0)

Wrapping this in a do-while ensures that our swap function is executed only once.

Using Macros in your C program can be useful at times, especially to rid your code of magic numbers with basic #defines. When creating functions for basic evaluation can be handy but it has its draw backs. There is a great article here outlining some of the pitfalls of C macros. As long as you are aware of what you are doing C macros can be very handy.