简体   繁体   中英

When to use the preprocessor to define functions in C?

When should I use the C preprocessor to define a function? Here's a quick example:

#define isUnderscore(ch) ((ch) == '_')

Over this:

// just to make the bool more clear.
typedef enum {
    false, true
} bool;

bool isUnderscore(char x) {
    return x == '_';
}

This may be a stupid question, but I can't find any results from a quick Google.

You normally use the preprocessor if you want to discard type-safety. isUnderscore as a macro will accept any type for ch for which == makes sense.

As a rule of thumb, don't use the preprocessor unless absolutely necessary: debugging functions implemented as preprocessor macros is difficult.

(Remember that function overloading is not available in C).

Starting from C99 you could write it as inline function:

#include <stdbool.h>

inline bool isUnderscore(char x) {
    return x == '_';
}

This gives you both safety and type-checking of normal functions as well as efficiency of function-like macros (though there is not guarantee on that).

From N1570 (C11 draft) 6.7.4/6 Function specifiers (with emphasis mine):

A function declared with an inline function specifier is an inline function . Making a function an inline function suggests that calls to the function be as fast as possible. 138) The extent to which such suggestions are effective is implementation-defined . 139)

The general rule is if you can do something in the language itself rather than the preprocessor then you should.

A few decades ago there might have been a performance improvement where the macro would be inline, but any compiler that you're likely to use will be do these trivial optimisations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM