why to use these weird nesting structure

2019-08-28 20:48发布

i'm trying to study the linux kernel and reading the kernel code, but i can't understand the structure they use for the page structure as shown below: i mean,why they use union nested in the struct which nested in the union (the code is simplified...)

struct page {
    unsigned long flags;
    struct address_space *mapping;

    struct {
        union {
            pgoff_t index;  
            void *freelist; 
        };

        union {
            unsigned counters;

            struct {

                union {

                    atomic_t _mapcount;
                    struct {
                        unsigned inuse:16;
                        unsigned objects:15;
                        unsigned frozen:1;
                    };
                };
                atomic_t _count;
            };
        };
    };
}

标签: linux kernel
1条回答
孤傲高冷的网名
2楼-- · 2019-08-28 21:05

It is used to bring clarity into the code. It will be easier to read and understand if members are grouped.

Since you are not using the 'sub-structures' in any other data-structure, they are nested. Else, they would be declared separate and included as members, like below:

    struct list_based{
                pgoff_t index;  
                void *freelist; 
    };

    struct page {
        unsigned long flags;
        struct address_space *mapping;
        struct list_based lpage;
    };

    struct sector {
        unsigned long sub sect;
        struct list_based lsect;
    };
查看更多
登录 后发表回答