why to use these weird nesting structure

和自甴很熟 提交于 2020-01-16 19:37:52

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/16397192/why-to-use-these-weird-nesting-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!