Understanding C Macro with Pointers

I’m a Java developer, I don’t know much about the syntax of C macros. I study Deitel and Deitel’s books, but that doesn’t help.

I can not understand the meaning of this macro:

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

dis a pointer to a structure, qis size_t.

The macro is used in this file .

Could you help me figure this out? What does this macro do? Why is it written the way it is written? Is there a clearer way to write this macro?

+4
source share
3 answers

whenever you write _GetFrontItem(d,q)in the source code, it will be replaced by a preprocessor in this line

(d)->itemCache + ( (q)*(d)->block_size + (d)->offset[q] % (d)->block_size )*(d)->itemSize

d , ->. , d, 3 , itemCache, block_size offset

, .

, :

#define _GetFrontItem(d,q) ( (d)->itemCache + ( (q)*(d)->block_size + \

antislash \ . , ( ), , . , !

+4

, . .

, , " " ( ) : (d->itemCache + something) &d->itemCache[something].

, (, google ):

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

..., . , , , , , .

+5

d struct. d->itemCache ( unsigned char s). , d->itemSize . , i ,

d->itemCache + i * d->itemSize

, , , i q

q * d->block_size + d->offset[q] % d->block_size

This is probably determined by the specifics of the data structure in question.

To make this macro more readable, you can split it into several macros

#define _GetItem(d, i)  ((d)->itemCache + (i) * (d)->itemSize)
#define _GetFrontIndex(d, q) ((q) * (d)->block_size + (d)->offset[q] % (d)->block_size)
#define _GetFrontItem(d, q) _GetItem(d, _GetFrontIndex(d, q))
+3
source

Source: https://habr.com/ru/post/1569090/


All Articles