Why should we typedef a struct so often in C?

后端 未结 15 2895
無奈伤痛
無奈伤痛 2020-11-21 23:58

I have seen many programs consisting of structures like the one below

typedef struct 
{
    int i;
    char k;
} elem;

elem user;

Why is i

15条回答
  •  离开以前
    2020-11-22 00:00

    Let's start with the basics and work our way up.

    Here is an example of Structure definition:

    struct point
      {
        int x, y;
      };
    

    Here the name point is optional.

    A Structure can be declared during its definition or after.

    Declaring during definition

    struct point
      {
        int x, y;
      } first_point, second_point;
    

    Declaring after definition

    struct point
      {
        int x, y;
      };
    struct point first_point, second_point;
    

    Now, carefully note the last case above; you need to write struct point to declare Structures of that type if you decide to create that type at a later point in your code.

    Enter typedef. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef during its definition might be a good idea since you can save some typing moving forward.

    typedef struct point
      {
        int x, y;
      } Points;
    
    Points first_point, second_point;
    

    A word of caution while naming your custom type

    Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.

提交回复
热议问题