Should we use macros, inline functions or just normal functions and trust the compiler?

148 views Asked by At

Would it be better to define the below functions as macro or inline functions? Or is it better to use normal functions and trust the compiler, to maintain (in my opinion) better readability?

typedef unsigned char byte;

void set_size_mark(byte size_mark, byte *ptr)
{
    *ptr += size_mark << 1;
}

byte get_size_mark(byte *ptr)
{
    return *ptr >> 1;
}
3

There are 3 answers

0
Basile Starynkevitch On

You probably should declare these as static inline functions and define them in a header file.

(Alternatively, enable link-time optimization by compiling and linking with gcc -flto -O2, using a recent GCC)

3
Adam Stelmaszczyk On

First of all, definitely not macros. Now, we have to choose between:

  1. Never writing inline.
  2. Writing inline sometimes.

GCC in the current version will decide for you whether the function should be inlined or not. So, why bother? That's why I would go for option 1. Shorter code and less time spent by writer(s) and reader(s) of the code.

4
user2008934 On

You should inline those. The compiler would almost certainly do this itself anyway.

The code is one line and is unlikely to create code bloat, so it is probably more efficient to inline. The compiler knows this, however, if this is incorrect I think the compiler can ignore the inline keyword.

Generally speaking you should avoid macros - They cause many unexpected problems and are usually just as bad as inline functions while being far harder to use. There are uses for macros, but this is definitely not the appropriate place for one.