c typechecking macro with statements within extensions

Started by
0 comments, last by SiCrane 12 years, 10 months ago
I've come across a strange macro in some C code and I can't understand how it works. I've figured out that the {} thing is a GCC extension which lets you put statements within expressions but the rest doesn't make any sense. If __dummy and __dummy2 are seperate objects, how can they ever have the same address? And how does the comparison affect anything?

/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
})
I trust exceptions about as far as I can throw them.
Advertisement
The address comparison will cause a compiler error if the type of x and type are different. That's all that the comparison is for.
Also, is there any advantage to macros like that over inline functions? It seems to me like C programmers are allergic to functions.
I trust exceptions about as far as I can throw them.
I found another macro that doesn't make sense. It's supposed to loop over a linked list, but as far as I can tell, it never reaches the value head. Why does it start with pos = (head)->next and not just pos = (head)? Am I missing something?


/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
I trust exceptions about as far as I can throw them.

This topic is closed to new replies.

Advertisement