简体   繁体   English

C结构:typedef值得怀疑!

[英]C Struct : typedef Doubt !

In the given code snippet, I expected the error symbol Record not found . 在给定的代码片段中,我期望错误symbol Record not found But it compiled and ran fine on Visual Studio 2010 Compiler. 但是它可以在Visual Studio 2010编译器上编译并运行良好。 I ran it as a C program from Visual Studio 2010 Command Prompt in the manner - 我以如下方式从Visual Studio 2010命令提示符中将其作为C程序运行-

cl Record.c cl Record.c
Record 记录

Now the doubt is, doesn't typedef check for symbols ? 现在的疑问是, typedef是否不检查符号? Does it work more like a forward declaration ? 它更像是forward declaration吗?

#include "stdio.h"
#include "conio.h"

typedef struct Record R;
struct Record
{
    int a;
};

int main()
{   
    R obj = {10};
    getch();
    return 0;
}

You can always refer to undefined structures, which is a typical way to implement linked lists, after all. 毕竟,您始终可以引用未定义的结构,这是实现链接列表的典型方法。 They just have to be defined when you want to make use of their fields. 您只需要在要使用它们的字段时定义它们。 This page contains some details. 此页面包含一些详细信息。

C does not find the symbol Record because it is declared later on the code, like if you were trying to use a function you declare past on the code without defining its prototype. C找不到符号Record,因为它是在代码的后面声明的,就像您试图使用一个函数,您过去在代码上声明而不定义其原型一样。

You can also combine the two declarations, and then it becomes: 您还可以组合两个声明,然后变为:

typedef struct Record
{
    int a;
} R;

It also works and, in my opinion, even better, not because it can be faster, but because it is smaller. 我认为它也可以工作,甚至更好,不是因为它可以更快,而是因为它更小。

typedef must be used after its first parameter has been defined. 在定义第一个参数后,必须使用typedef

struct Record
{
    int a;
};
typedef struct Record R;

or 要么

typedef struct Record
{
    int a;
} R;

If you need to use struct Record within the struct, just use struct Record : 如果您需要在struct Record中使用struct Record ,只需使用struct Record

typedef struct Record
{
    struct Record *next;
}
typedef struct Record R;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM