arunmoezhi
arunmoezhi

Reputation: 3200

convert a one line function to a macro in c

I have a function which I want to convert to a macro without violating type safety

#define UINTPTR_MAX_XOR_WITH_1 (uintptr_t) (UINTPTR_MAX ^ 1)
struct node
{
    unsigned long key;
    tbb::atomic<struct node*> lChild;    //format <address,flagBit>
    tbb::atomic<struct node*> rChild;    //format <address,flagBit>
};

struct node* getAddress(struct node* p)
{
    return (struct node*)((uintptr_t) p & UINTPTR_MAX_XOR_WITH_1);
}

main()
{
    nodeAddr = getAddress(node);
    lNodeAddr = getAddress(node->lChild);
}

I try to replace getAddress() function with this macro. I know this macro definition is wrong.

#define getAddress(p) ((struct node*) (uintptr_t) p & UINTPTR_MAX_XOR_WITH_1)

I read this post Macro vs Function in C But still couldn't figure how to do it for this case

Upvotes: 1

Views: 315

Answers (1)

pts
pts

Reputation: 87391

This is almost equivalent, except that the macro is more permissive than the function when type-checking its argument:

#define getAddress(p) ((struct node*) ((uintptr_t) (struct node*)(p) & UINTPTR_MAX_XOR_WITH_1))

Some C compilers accept static inline, that's not a macro, but it's equivalent to the original function, and will get inlined most of the time in practice:

static inline struct node* getAddress(struct node* p) {
  return (struct node*)((uintptr_t) p & UINTPTR_MAX_XOR_WITH_1);
}

Upvotes: 1

Related Questions