简体   繁体   中英

C Struct : typedef Doubt !

In the given code snippet, I expected the error symbol Record not found . But it compiled and ran fine on Visual Studio 2010 Compiler. I ran it as a C program from Visual Studio 2010 Command Prompt in the manner -

cl Record.c
Record

Now the doubt is, doesn't typedef check for symbols ? Does it work more like a 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.

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.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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