..back..

Inline Functions vs Macros

Macros

A macro is a fragment of code which has been given a name1. If we use the name of the fragment somewhere in the code, then it will be replaced by the whole fragment. Basically it is a simple text replacement in the code.

Definition of macro.

#define name replacement_text

Macros were/are often used for defining symbolic constants (Object-like Macros).

#define MAX_SIZE 255
char buff[MAX_SIZE];

Nowadays for constants it is better to use const keyword. They are handled by the compiler and add benefit of type safety 2.

const int MAX_SIZE = 255;

With macros we can also define a function (Functin-like Macros):

#define MAX(a, b) ((a) > (b) ? (a) : (b))
int x = MAX(1, 2);

Disadvantages

There are few pitfalls, when using macros:

Parentheses: We cannot forget parentheses to preserve the order of evaluation:

#define SQRT(a) a * a /* WRONG */
SQRT(z+1); /* What happens ? */

Side effects: This will increment the larger twice:

MAX(i++, j++) /* WRONG */

Self-Referential macro:

#define foo (4 + foo) /* WRONG */

There are many more exaples, but for these reasons it is better to use inline functions, which where introduced in C99.

What is an inline function?

An inline function is a function declared with the inline keyword. This keyword serves as a suggestion to the compiler to replace the function call with the actual code of the function during compilation.

This process is known as “inlining.” By doing so, it can eliminate the overhead associated with function calls, potentially reducing the execution time of a program. However, it’s important to note that the inline keyword is a request, not a command. The compiler may choose to ignore it if it deems inlining inappropriate.

Here is an example 3:

inline void swap(int *m, int *n)
{
    int tmp = *m;
    *m = *n;
    *n = tmp;
}

Function would be called like this:

swap(&x, &y);

If the compiler decides to optimize, the call would be replaces for:

int tmp = x;
x = y;
y = tmp;