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 开发者_StackOverflow社区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;
精彩评论