Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undeclared struct causes no warnings

Tags:

c++

c

The following code compiles fine without any warnings on gcc.

Note that there's no forward declaration for the struct. Is this valid C and/or C++ code?

struct Foobar* f;
struct Foobar* fun() { return 0; }

int main() { f = 0; fun(); return 0; }
like image 800
Karoly Horvath Avatar asked Sep 08 '15 14:09

Karoly Horvath


2 Answers

This called an opaque structure and is not an error. Since all struct pointers are equally large in C, there is no need to know what fields the struct has as long as you just manipulate pointers to it.

Try defining a variable struct Foobar (no pointer) and you will get an incomplete type error.

This enables you to have types with private fields e.g. the FILE type from stdio.h.

like image 104
jforberg Avatar answered Oct 22 '22 06:10

jforberg


Valid in C.

struct Foobar* f;

is the same as:

struct Foobar;
struct Foobar* f;

In C it declares an incomplete type struct Foobar and it declares a pointer object to an incomplete type.

The type can be completed in another translation unit. (In C there are 3 kinds of type: object, function and incomplete).

You cannot create objects of an incomplete type or get the size of the type:

struct Foobar x; // not valid
sizeof (struct Foobar); // not valid

but you can create pointers to incomplete types (struct Foobar* g;) or typedef (typedef struct Foobar Foobar;).

like image 41
ouah Avatar answered Oct 22 '22 07:10

ouah