【问题标题】:Difference between structure instance and name结构实例和名称的区别
【发布时间】:2014-02-22 14:37:49
【问题描述】:

有什么区别

typedef struct complex {
    int x;
    int y;
};

typedef struct complex { 
    int x;
    int y;
} comp;

第二种情况下额外的comp 有什么作用? 我尝试在第一种情况下定义complex 类型的新变量,在第二种情况下使用comp,两者都产生了相同的结果...请帮助!

【问题讨论】:

    标签: c data-structures struct typedef


    【解决方案1】:

    第一个typedef没用,编译时可能会警告你。

    在第二个typedef 之后,每当您使用struct complex 作为类型时,您都可以使用comp 来代替。您可以将第二个代码修改为这种等效形式:

    struct complex { 
        int x;
        int y;
    };
    typedef struct complex comp;
    

    您可以看到struct complex 定义了一个类型,而typedef 给了它一个替代名称。

    【讨论】:

      【解决方案2】:

      typedef 的目的是为由一个或多个类型组件组成的类型声明分配一个简单的名称。

      在第一个声明中,您没有为名为 complex 的结构分配任何名称。因此编译器会产生一个警告:

      i.e. warning: declaration does not declare anything 
      

      通常,在将 typedef 与结构 [ 或 unions ] 一起使用时,最好(不那么冗长)使用未命名的结构,如下所示:

      typedef struct {int x; int y;} complex;
      

      【讨论】:

        【解决方案3】:
        struct complex {
            int x;
            int y;
        } comp;
        

        这是创建复杂类型变量的简写。 comp 之前存在;所以它被视为复杂类型的变量。也看下面的代码

        struct {
            int x;
            int y;
        } comp;
        

        您也可以使用创建其结构类型变量的旧编译器来执行此操作。

        【讨论】:

        • 请注意,'变量名'在typedef下有不同的含义,这不是你描述的情况。
        【解决方案4】:

        长话短说:

        struct complex {
            int x;
            int y;
        };
        // forces you to use :
        struct complex c;
        

        但是:

        typedef struct complex {
            int x;
            int y;
        } comp;
        // allows you to use :
        comp c;
        

        Typedef 只是可读性的问题

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-25
          • 2019-03-29
          • 2015-10-20
          • 1970-01-01
          • 2020-09-19
          • 1970-01-01
          相关资源
          最近更新 更多