Syntax of typedef struct

Asked

Viewed 3,131 times

3

What’s the difference between writing typedef struct "nome1"{}"NOME2";, as implemented in a chained list; and typedef struct{}"NOME1";, as implemented in sequential list that I saw.

I’ve also come across struct "nome1"{}typedef struct "nome1" "nome2";. Is there any pattern about writing the name in high box?

Sequential list:

typedef struct{
  char nome[30];
  char posicao[30];
  int  nrCamisa;
}JOGADOR;

typedef struct{
  JOGADOR vetor[MAX];
  int NroElem;
}ELENCO;

Simply chained list:

typedef struct{
  char nome[30];
  char posicao[30];
  int  nrCamisa;
}JOGADOR;

typedef struct no{
  JOGADOR info;
  struct no* prox;
}ELENCO;

1 answer

5


typedef creates a new type, it has nothing to do with the structure. You can do so:

typedef int Inteiro

He’s creating a new guy named Inteiro which will be based on the type int.

Then you can do it too:

struct exemplo {
    int x;
}

typedef struct exemplo Exemplo;

Which is the same as doing:

typedef struct exemplo {
    int x;
} Exemplo;

I put in the Github for future reference.

So there exemplo is the name of the structure, and Exemplo is the name of the guy.

Note that I prefer to use type names starting with uppercase or Camelcase. There are those who like that of ALL CAPS, there are those who like everything tiny, there is no universal standard.

A structure need not have a name. Of course if it has no name or can only be used once, it must be defined in a typedef which will then be used to create a data based on the anonymous structure.

I’m not particularly fond of naming the structure on a typedef. Unless the type itself is used within the structure, it creates a problem, because the type cannot be used in a structure that defines it, the type does not yet exist when the structure is being defined. So in the last example it has the name because of this. The structure references itself before defining ELENCO, then this name cannot be used, you need to use the struct no.

Note that the structure name exists only in the scope of a struct whereas the name of the type is global.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.