ctypedef

How does the typedef struct work syntactically?


I am new to this, so I apologize if I'm being dense. I'm having trouble understanding how to use typedef. Let's say I have the following command:

typedef struct {
    char pseudo[MAX_SIZE] ;
    int nb_mar ;
    } player ;

This creates a type called player which comprises of a chain of characters, and an int, correct?

Now, if we have this line of code:

struct set_of_players {
    player T[NB_MAX_JOUEURS] ;
    int nb ;
    }; 

I don't understand what this does? I would assume it creates a variable of type struct set_of_players, but what is it called? Usually when I see this kind of command, there's a word after the closed amplesand representing the variables name, but here it has nothing; I don't get it. Would this even work if I haven't done a typedef struct for set_of_players?

Finally, I have this line of code that I don't understand:

typedef struct set_of_players players;

I quite honestly have no idea what this even means. I'm assuming this is the typedef that I need to make the previous command make sense, but I don't even know what it does.

Again, I'm sorry if I'm looking at this the wrong way, and for the poor formatting. Any help would be greatly appreciated, thank you.


Solution

  • The typedef statement allows you to make an alias for the given type. You can then use either the alias or the original type name to declare a variable of that type.

    typedef int number;
    

    This creates an alias for int called number. So the following two statements declare variables of the same type:

    int num1;
    number num2;
    

    Now using your example:

    typedef struct {
        char pseudo[MAX_SIZE] ;
        int nb_mar ;
    } player ;
    

    This creates an anonymous struct and gives it the alias player. Because the struct doesn't have name, you can only use the alias to create a variable of that type.

    struct set_of_players {
        player T[NB_MAX_JOUEURS] ;
        int nb ;
    }; 
    

    This creates a struct named struct set_of_players, but does not declare a typedef nor does it declare a variable of that type. Also notice that one of the fields is an array of type player, which we defined earlier. You can later declare a variable of this type as follows:

    struct set_of_players my_set_var;
    

    This line:

    typedef struct set_of_players players;
    

    Creates an alias for struct set_of_players called players. In this case the struct is not defined at the same time as the typedef but is defined elsewhere. So now you can declare a variable of this type like this:

    players my_set_var;
    

    Which is the same as the version using the full struct name.