Home / Articles / Macro Overloading

Macro Overloading

Macro and Function with the Same Name

In C, a macro and a function can have the same name. The preprocessor expands macros by textual substitution, but if the macro name is wrapped in parentheses at the call site, the preprocessor does not recognise it as a macro invocation and leaves it alone — allowing the function version to be called instead.

A classic example is putchar, which is implemented both as a macro (for performance) and as a real function:

putchar('M');    /* Calls the macro version */
(putchar)('F');  /* Calls the function version */

The parentheses around putchar in the second call prevent the preprocessor from performing macro expansion. The compiler then sees a normal function call.

Disabling a Macro with #undef

If you want to permanently disable a macro and use only the function, use #undef:

#undef putchar
putchar('F');   /* Now always calls the function */

Use Cases

The ability to have both a macro and a function with the same name is useful when: