cstructstandardstypedef

why to use an underscore for a struct in c?


In the source code below, could somebody explain the rational (why is it good programming practice to typedef the struct _lwm2m_object_t with the new name lwm2m_object_t? All it does is drop the underscore? Why is an underscore used in the first instance?

typedef struct _lwm2m_object_t lwm2m_object_t;

typedef uint8_t (*lwm2m_read_callback_t) (lwm2m_uri_t * uriP, char ** bufferP, int * lengthP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_write_callback_t) (lwm2m_uri_t * uriP, char * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_execute_callback_t) (lwm2m_uri_t * uriP, char * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_create_callback_t) (lwm2m_uri_t * uriP, char * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_delete_callback_t) (uint16_t id, lwm2m_object_t * objectP);
typedef void (*lwm2m_close_callback_t) (lwm2m_object_t * objectP);


struct _lwm2m_object_t
{
    uint16_t                 objID;
    lwm2m_list_t *           instanceList;
    lwm2m_read_callback_t    readFunc;
    lwm2m_write_callback_t   writeFunc;
    lwm2m_execute_callback_t executeFunc;
    lwm2m_create_callback_t  createFunc;
    lwm2m_delete_callback_t  deleteFunc;
    lwm2m_close_callback_t   closeFunc;
    void *                   userData;
};

Solution

  • Actually if you use

    typedef struct lwm2m_object_t lwm2m_object_t;
    
    struct lwm2m_object_t {
    //
    }
    

    It will still be allowed by C. This is because the structure names and the typedef identifiers have different namespaces. Please see Why doesn't ANSI C have namespaces? for information about namespaces in C.

    However, many professional users avoid this and use different names for structures and typedefs. MISRA1 also disallows this.

    Rule 5.6 (advisory): No identifier in one name space should have the same spelling as an identifier in another name space, with the exception of structure member and union member names. [MISRA C 2004]

    The use of underscore is just a convention that some people follow. You can follow other conventions, e.g.

    typedef struct sTag_lwm2m_object_t lwm2m_object_t;
    
    struct sTag_lwm2m_object_t {
    //
    }
    

    1 https://en.wikipedia.org/wiki/MISRA_C