Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: What does this macro mean?

Tags:

c

gcc

macros

How do you read the second line of this macro? What does (type *)0 mean in this context?

#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
like image 517
zer0stimulus Avatar asked Nov 21 '11 04:11

zer0stimulus


People also ask

What do you mean by macro?

A macro is an automated input sequence that imitates keystrokes or mouse actions. A macro is typically used to replace a repetitive series of keyboard and mouse actions and used often in spreadsheets and word processing applications like MS Excel and MS Word. The file extension of a macro is commonly . MAC.

What are macros used for in C?

In C, the macro is used to define any constant value or any variable with its value in the entire program that will be replaced by this macro name, where macro contains the set of code that will be called when the macro name is used in the program.

What does ## mean in C macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.


1 Answers

You're finding the type of ((type *)0)->member. It's not actually dereferencing the pointer (that would be madness, I tell you. Madness!)

It's a weirdness of C. Maybe it would make more sense if they wrote typeof(type.member) but sadly that is not allowed.

like image 139
Robert Martin Avatar answered Sep 28 '22 13:09

Robert Martin