简体   繁体   中英

What is the application of ampersand within C macros?

I'm reading linux/list.h header, it have this macro :

#define LIST_HEAD_INIT(name) { &(name), &(name) }

I want to know when I write LIST_HEAD_INIT(birthday_list) how the macro expanded?

LIST_HEAD_INIT is used to initialize the list head structure instance.

#define LIST_HEAD_INIT(name) { &(name), &(name) } 
#define LIST_HEAD(name) \
        struct list_head name = LIST_HEAD_INIT(name)

from linux/types.h:

struct list_head {
    struct list_head *next, *prev;
};

This is expanded to

struct list_head name = { &(name), &(name) }

As you can see, it is expanded and now the "prev" and "next" pointers fields of structure instance "name" points back to itself. This is how the list head is initialized.

After intialization LIST_HEAD(birthday_list) is birthday_list.prev = birthday_list.next = &birthday_list "birthday_list" is the head node of the double linklist which is empty and instead of leaving the prev and next pointer to NULL, they have been set to point back to the head node.

struct list_head birthday_list = {
    .next = &birthday_list,
    .prev = &birthday_list
}

There's nothing special about ampersands, they're just another token. LIST_HEAD_INIT(birthday_list) gets expanded as { &(birthday_list), &(birthday_list) }

You can just look at the output of the preprocessor directly if you want to check this or other macro expansions yourself. GCC has the -E argument to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM