• Why should we typedef a struct so often in C?


    https://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c

    As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

    Stuff like

    typedef struct {
      int x, y;
    } Point;
    
    Point point_new(int x, int y)
    {
      Point a;
      a.x = x;
      a.y = y;
      return a;
    }
    

    becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef, is the case I guess.

    Also note that while your example (and mine) omitted naming the struct itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:

    typedef struct Point Point;
    
    Point * point_new(int x, int y);
    

    and then provide the struct definition in the implementation file:

    struct Point
    {
      int x, y;
    };
    
    Point * point_new(int x, int y)
    {
      Point *p;
      if((p = malloc(sizeof *p)) != NULL)
      {
        p->x = x;
        p->y = y;
      }
      return p;
    }
    

    In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

    UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

  • 相关阅读:
    第七周
    跳ajax方式进行前后台交互之后台代码要怎么写
    写代码要注意细节,无谓的找前台bug
    mysql复习增删改查
    jquery获取value值
    sql查阅每一月的数据
    登录模块需要用到session留底
    前后台使用ajax传list的时候,用value[] 获取值
    Datables wrning(table id='example'):Cannot reinitialise DataTable.
    动态规划1
  • 原文地址:https://www.cnblogs.com/rsapaper/p/10193240.html
Copyright © 2020-2023  润新知