non-trivial designated initializers not supported

前端 未结 6 1616
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 04:23

I have a structure as follows:

struct app_data
{
    int port;
    int ib_port;
    unsigned size;
    int tx_depth;
    int sockfd;
    char *servername;
           


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 04:58

    I have noticed my GCC compiler has some trick to accept .fieldname=value assigments but will only compile if fields come in the same order they are declared in the struct.

    I was able to init this struct in two ways. The one with names improves readability and reduces the risk of assigning the wrong data if the struct field order is later changed.

    //Declare struct
    typedef struct
    {
        uint32_t const * p_start_addr;
        uint32_t const * p_end_addr;
        fs_cb_t  const   callback;    
        uint8_t  const   num_pages;  
        uint8_t  const   priority;
    } fs_config_t;
    
    //Assign unnamed
    fs_config_t fs_config  
    {
        (uint32_t*)0x00030000,  // uint32_t const * p_start_addr;
        (uint32_t*)0x00038000,  // uint32_t const * p_end_addr;         
        fs_evt_handler,         // fs_cb_t  const   callback;
        8,                      // uint8_t  const   num_pages;
        0xFE                    // uint8_t  const   priority;               
    };
    
    //Assign to named fields
    static fs_config_t fs_config1  
    {
        .p_start_addr = (uint32_t*)0x00030000,
        .p_end_addr = (uint32_t*)0x00038000,            
        .callback = fs_evt_handler,
        .num_pages = 8,
        .priority = 0xFE                
    };      
    

    The rule of thumb is:

    1. Assign to .name=value fields
    2. Assign in the order they where declared
    3. Include all fields in the assigment

提交回复
热议问题