chapman
chapman

Reputation: 929

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.

Upvotes: 2

Views: 122

Answers (3)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37934

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)

Upvotes: 2

luckykaa
luckykaa

Reputation: 166

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.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

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).

Upvotes: 3

Related Questions