C Typedef and Struct Question

前端 未结 5 1864
别那么骄傲
别那么骄傲 2020-11-28 11:39

What\'s the difference between these two declarations, and is one preferred over the other?

typedef struct IOPORT {  
    GPIO_TypeDef* port;  
    u16               


        
5条回答
  •  暖寄归人
    2020-11-28 12:19

    For the sake of readability it's preferred to express the original example in a form such as:

    typedef struct IOPORT_t {  
        GPIO_TypeDef* port;  
        u16           pin;  
    } IOPORT; 
    

    ....which emphasizes the difference between type and instance.

    Furthermore, if you want to add initialisers you can do something like:

    typedef struct IOPORT_t {  
        GPIO_TypeDef* port;  
        u16           pin;  
    } IOPORT;
    
    struct IOPORT_t IOPORT2 = {
        .port = NULL,
        .pin = 25
      };
    

    or you can lose the typedef to initialise it directly:

    struct IOPORT_t {  
        GPIO_TypeDef* port;  
        u16           pin;  
    } IOPORT = {
        .port = NULL,
        .pin = 24
      };
    
    struct IOPORT_t IOPORT2 = {
        .port = NULL,
        .pin = 25
      };
    

提交回复
热议问题