Search code examples
cmacrosc-preprocessorinline-functions

Convert an inline function to a macro


I have a 1 line inline function which is part of a hotspot in my code. I would like to see if changing this to a macro would be beneficial. Writing as a function I did not have to worry about side effects. But how do I write a macro for this without side effects?

#define FLAG1_BIT 4
struct node
{
    unsigned long key;
    struct node* child[K];      //format <address,flag1,flag2,flag3>
};

static inline bool isFlag1Set(struct node* p)
{
    return ((uintptr_t) p & FLAG1_BIT) != 0;
}

Solution

  • First, keep in mind, I can see no reason why the compiler wouldn't inline it, so there's a every good chance this exercise will accomplish nothing at all.

    The first rule to avoiding side-effects is to ensure that the parameter appears only once in the definition. Next, in the definition, wrap the parameter and the whole definition in parenthesis:

    #define isFlag1Set(p)   (((uintptr_t) (p) & FLAG1_BIT) != 0)