Undefined structure type?

2 posts / 0 new
Last post
xenic's picture
Last seen: 2 years 2 months ago
Joined: 2011-05-07 04:52
Undefined structure type?

While debugging a program I noticed a structure declaration that contains an undefined type but GCC isn't flagging it with a warning or error. Why would that be the case?

Here is an example using an undefined structure type of 'notdef':

struct Notdef *mystruct;

Notdef isn't defined anywhere but the declaration isn't flagged.

On the other hand if I declare a simple pointer the same way it gets flagged as an error by GCC.

Notdef *myptr;

gets flagged as an error.

Can anyone explain why the structure declaration doesn't get flagged as an error?

salass00's picture
Last seen: 2 months 6 days ago
Joined: 2011-02-03 11:27
Re: Undefined structure type?
  1. struct Notdef *mystruct;

This can be seen as a forward declaration of the structure Notdef. As it's a pointer the compiler doesn't need to know the size or contents of the structure yet.

  1. Notdef *myptr;

In this case the compiler can't know if this is a struct, a class, an enum, a union, a typedef or whatever else it could be since you haven't specified it so it will produce an error.

OTOH this code will work:

  1. struct Notdef; // forward declaration
  3. Notdef *myptr;

Leaving out struct keyword as in the last two code fragments is only allowed in C++ code and not in plain C. In C the only way to get rid of 'struct' is to use a typedef.

Log in or register to post comments