ctypedefc11

Use of comma in a typedef declaration?


Is this declaration C99/C11 compliant ?

typedef struct element {
    char *data; 
    struct element* next;
} element, *list, elements[5];

I could not find why it works in the standard.


Solution

  • Yes, it is standard compliant. typedef declarations are like normal declarations except the identifiers declared by them become type aliases for the type of object the identifier would be if the declaration had no typedef in it.

    So while

    int integer, *pointer_to_integer;
    

    declares an int object named integer and an int * object named pointer_to_integer

    typedef int integer, *pointer_to_integer;
    

    would declare an int-typed type alias named integer and an int *-typed type alias named pointer_to_integer.

    From a syntactical perspective, though not functionally, typedef is just a (fake) storage classifier (like extern, auto, static, register or _Thread_local).

    Your declaration

    typedef struct element {
        char *data; 
        struct element* next;
    } element, *list, elements[5];
    

    is slightly more complicated because it also defines the struct element data type but it's equivalent to:

    struct element {
        char *data; 
        struct element* next;
    }; 
    // <= definition of the `struct element` data type
    // also OK if it comes after the typedefs
    // (the `struct element` part of the typedef would then
    // sort of forward-declare the struct )
    
    /*the type aliases: */
    typedef struct element 
          element, *list, elements[5];
    

    -- it declares element as a type alias to struct element, list as a type alias to struct element * and elements as a type alias to struct element [5].