Jump to content
  • Advertisement
Sign in to follow this  
Storyyeller

c typechecking macro with statements within extensions

This topic is 2571 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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; \
})

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Hidden
Also, is there any advantage to macros like that over inline functions? It seems to me like C programmers are allergic to functions.

Share this post


Link to post
Hidden
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)

Share this post


Link to post
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!