What is the use of Struct Tag name in C programming?

前端 未结 3 637
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:39

I want to know the actual use of struct tag_name in C programming. Without using the tag_name also i was getting output as with use of tag_name. I want the exact reason behind t

3条回答
  •  执念已碎
    2021-02-09 16:29

    A struct declaration tells the compiler how a struct looks like and optionally gives that struct a name. If you want to use a struct as a "type" in your code, it requires a name:

    struct coordinate {
      int x;
      int y;
    };
    
    // Can now be used as a return type:
    struct coordinate getCoordinate ( ) { ... }
    
    // Can now be used as an argument:
    void drawAtPoint ( struct coordinate point ) { ... }
    
    // Can be used to create new constants or variables:
    const struct coordinate kOrigin = { 0, 0 };
    struct coordinate lastViewPosition;
    

    Alternatively you can create a nameless struct and explicitly define it to be a new type using a type definition:

    typedef struct {
      int x;
      int y;
    } coordinate;
    
    // Can now be used as a return type:
    coordinate getCoordinate ( ) { ... }
    
    // Can now be used as an argument:
    void drawAtPoint ( coordinate point ) { ... }
    
    // Can be used to create new constants or variables:
    const coordinate kOrigin = { 0, 0 };
    coordinate lastViewPosition;
    

    But if you don't do either one, you cannot use that struct as a type since in C, the type of a struct is defined by its name and not by its data layout.

    The following is valid C code:

    struct coordinate {
      int x;
      int y;
    };
    
    struct coordinate startCoord = { 20, 80 };
    struct coordinate endCoord = startCoord;
    

    Yet the following is not:

    struct {
      int x;
      int y;
    } startCoord = { 20,  80 };
    
    struct {
      int x;
      int y;
    } endCoord = startCoord;
    

    Compiler will fail with an error. It seems as if startCoord and endCoord have the same type in both examples, but that's not true. Two structs don't denote the same type just because they have an equal memory layout or equal field names. For a C compiler, startCoord and endCoord have different types in the later example and thus you cannot assign them as shown above as this requires that both of them have the same type.

    So the only situation where you can skip naming your structs is when you directly declare variables of that struct type and there is no requirement to ever refer to that struct again as a data type throughout your code.

提交回复
热议问题