【问题标题】:Why does this C code compile? C struct typdef为什么这个 C 代码可以编译? C 结构类型定义
【发布时间】:2012-02-29 05:15:35
【问题描述】:

我写了以下程序:

typedef struct blahblah {
    int x;
    int y;
} Coordinate;

int main () {
   Coordinate p1;
   p1.x = 1;
   p1.y = 2;

   //blah blah has not been declared as a struct, so why is it letting me do this?
   struct blahblah p2;
   p2.x = 5;
   p2.y = 6; 
}

谁能给我解释一下这是怎么回事?

【问题讨论】:

  • 我不太明白。 struct blahblah 当然 被声明为结构,它就在您示例的顶部。

标签: c compiler-construction struct


【解决方案1】:

你说:

blah blah 没有被声明为结构体,

其实有:

typedef struct blahblah {
    int x;
    int y;
} Coordinate; 

这既是 typedef Coordinate,也是 struct blahblah 的定义。定义说的是:

  • 定义一个名为struct blahblah的数据类型
  • 它有两个成员,int xint y
  • 另外,创建一个名为Coordinate 的类型定义,它等同于struct blahblah

【讨论】:

    【解决方案2】:

    你的结构声明相当于

    struct blahblah {
        int x;
        int y;
    };
    typedef struct blahblah Coordinate;
    

    由于这会为结构类型 (struct blahblah) 和 Coordinate 创建两个名称,因此两个类型名称都可以用于声明变量。

    【讨论】:

      【解决方案3】:

      typedef 定义了新的用户定义数据类型,但不会使旧定义无效。例如typedef int INT 不会使int 失效。同样,您的 blahblah 仍然是有效的已定义结构!而坐标只是一种新类型!

      【讨论】:

        【解决方案4】:

        您在 typedef 中将 blahblah 声明为结构。 typedef 只是一种简单的引用结构 blahblah 的方法。但是 struct blahblah 存在,这就是为什么你可以给它一个 typedef。

        【讨论】:

          【解决方案5】:

          typedef 用于创建一种类型到另一种类型的别名。您实际上是在 typedef 本身中声明了“struct blahblah”。这有点令人困惑,但正如@Timothy 和其他人所指出的那样,这是一个有效的定义。

          【讨论】:

            猜你喜欢
            • 2019-09-09
            • 1970-01-01
            • 1970-01-01
            • 2021-08-15
            • 1970-01-01
            • 2014-03-01
            • 2010-11-24
            • 1970-01-01
            • 2010-10-24
            相关资源
            最近更新 更多