0

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;
}
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • try to put `typedef struct Record R;` under `struct Record ...` – xhan Jan 15 '11 at 15:40
  • @xhan - If I do it, it is a meaningful because symbol `Record` is found earlier. Thanks. – Mahesh Jan 15 '11 at 15:42
  • Your code ran fine under GCC (had to change getch to getchar) and VS2005. I suspect your findings are right. – karlphillip Jan 15 '11 at 15:43
  • possible duplicate of [What's the syntactically proper way to declare a C struct?](http://stackoverflow.com/questions/4698600/whats-the-syntactically-proper-way-to-declare-a-c-struct) – Jens Gustedt Jan 15 '11 at 16:10

3 Answers3

1

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.

Peter Eisentraut
  • 35,221
  • 12
  • 85
  • 90
0

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.

Giuliano
  • 172
  • 9
0

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;
peoro
  • 25,562
  • 20
  • 98
  • 150