Macros or Functions

In C, a macro is a preprocessor directive that creates a shortcut, often a one-line expression to be inserted elsewhere in the code. Macros can make code more readable, but they can have a negative effect when implemented in a clumsy manner.

In the following code, you see the age-old max() function:

#include <stdio.h>

int max(x,y)
{
    if( x > y )
        return(x);
    else
        return(y);
}

int main()
{
    int a,b;

    printf("Input two numbers separated by a space: ");
    scanf("%d %d",&a,&b);

    printf("%d is greater\n",max(a,b));

    return(0);
}

Here’s a sample run:

Input two numbers separated by a space: 26 88
88 is greater

The max() function can also be written:

int max(x,y)
{
    return( x > y ? x : y );
}

The output is the same. Yet, something about a one-line function seems odd to me. In this Lesson’s example, the function isn’t required, but assume max() is part of a longer program where it’s called from multiple parts of the code. Even then, a one-line function seems rather silly.

As an alternative, and with no particular advantage one way or another, you can declare max() as a macro. Use the #define preprocessor directive at the start of the source code file:

#define max(x,y) x > y ? x : y

To create this macro, I scrunched up the max() function, removing the braces and semicolon at the end of the statement. What’s left is the macro max(), which takes two arguments, x and y. The arguments are expanded into the ternary operator are shown above: The macro itself is max(x,y) (no spaces) and everything on the rest of the line is the macro’s definition, what will be stuck into the code where the macro appears.

Remember: Many of the “functions” you regularly use in C are defined as macros, such as getchar() and putchar(). Still, they look like and operate like functions within the code. Technically, they’re macros.

In practice, I define my macros as ALL CAPS, just like defined constants. That way I know that the “function” is really a macro. Also, I feel it clues in anyone else reading my code that MAX() is a macro, and not a function they must hunt for elsewhere in the source code.

In next week’s Lesson, I use various macros to carry out mathematical operations at the binary level. It’s this kind of nerdy joy that makes me appreciate the C language.

Leave a Reply