Search code examples
cstructtypedefc89

Variable declaration at the end of typedef structure definition


We know that struct objects can be declared at the end of structure definition like so :

struct vertex
{
float x,y,z;
}v1;

Is such a declaration of an object like v1 possible while using typedef struct?

typedef struct vertex
{
float x,y,z;
} vertex;

Is it mandatory to declare objects separately now with

vertex v1;

can they not be appended at the end of struct definition in this case?


Solution

  • No, it cannot be.

    typedef is used for creation of an alias / synonym for another type. It cannot be used for declaration of variables.

    typedef struct ver
    {
    float x,y,z;
    } vertex;
    

    Here, vertex is same as struct ver (I changed the name slightly for better understanding).

    Once the type (alias) is created, you use that to create a variable using another identifier, like

    vertex v;
    struct ver v1;