Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a C macro with pointers

Tags:

c

pointers

macros

I am a Java developer, I am not very familiar with the syntax of C macros. I am studying on Deitel & Deitel book, but it does not help.

I can't understand the meaning of this macro:

#define _GetFrontItem(d,q)  ( (d)->itemCache + ( (q)*(d)->block_size +  \
                              (d)->offset[q] % (d)->block_size )*(d)->itemSize)

d is a pointer to a struct, q is a size_t.

The macro is used in this file.

Can you please help me understand it? What does this macro accomplish? Why is it written in the way it is written? Is there a more clear way to write this macro?

like image 546
Vitaly Olegovitch Avatar asked Dec 08 '22 05:12

Vitaly Olegovitch


1 Answers

I have to say, that is a damn ugly macro. Moving on.

What the macro does is compute an index into the struct's "item cache" (whatever that is), and returns a pointer to it : (d->itemCache + something) is equivalent to &d->itemCache[something].

The macro is thus equivalent to the following inline function (identifiers sweeped from a google match here) :

static inline char *_GetFrontItem(Data *d, size_t q) {
    return &d->itemCache[
        d->itemSize * (q * d->block_size + d->offset[q] % d->block_size)
    ];
}

... which is a bit more intelligible. Why it is a macro in the first place is probably because this is legacy code, from the old times when inline functions simply didn't exist.

like image 73
Quentin Avatar answered Dec 15 '22 01:12

Quentin