简体   繁体   中英

Undeclared struct causes no warnings

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; }

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 eg the FILE type from stdio.h.

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; ).

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