1

In C language, what is the meaning of struct Animal; in line # 6?
Is it legal in C89 or C99 or C11?

struct Animal {
    char *name;
    int age;
};

struct Cat {
    struct Animal;   // line 6
    int category;
};

Thanks!

Azeem
  • 11,148
  • 4
  • 27
  • 40
Ring.Yee
  • 56
  • 4
  • I think it says "there is a type `struct Animal`", and that's all. It doesn't do anything useful because line 1 already said that. When I compile it, I get `x.c:9:18: error: declaration does not declare anything [-Werror]` — `struct Animal;` which is what I'd expect. It would be a warning if I didn't compile with `-Werror`. – Jonathan Leffler Nov 20 '18 at 04:54
  • I've tried the code in VS2015 with a .c file, and it compiled ok, and output: sizeof(struct Animal): 8 sizeof(struct Cat): 12 which looks like there is an "struct Animal" entity in struct cat. So I'm not sure is it legal in C89 or C99? – Ring.Yee Nov 20 '18 at 05:01
  • It's dubious, but legal. I have GCC set to very fussy, and any warnings it produces are treated as errors. – Jonathan Leffler Nov 20 '18 at 05:02
  • In clang, it looks like meaning nothing, I've tried the code in xcode9, and it outputs: sizeof(struct Animal): 16 sizeof(struct Cat): 4 – Ring.Yee Nov 20 '18 at 05:08
  • Working on a Mac, 64-bit compilation, and suppressing the `-Werror` option, I get size of Animal as 16 and size of Cat as 4, which is exactly what I'd expect. Your result on VS2015 is curious — I find it hard to explain how you got that result. – Jonathan Leffler Nov 20 '18 at 05:14

1 Answers1

5

It doesn't mean much of anything -- and in fact it's a constraint violation.

The language grammar allows

struct Animal;

in place of a member declaration inside a struct or union declaration. But it violates a language rule (N1570 6.7.2.1 paragraph 2):

A struct-declaration that does not declare an anonymous structure or anonymous union shall contain a struct-declarator-list.

This is a "constraint", which means that violating it requires a diagnostic. (A non-fatal warning message qualifies as a diagnostic.)

If you had written:

struct Cat {
    struct Animal foo;
    int category;
};

then the foo would be a "declarator". The constraint I quoted above means you're not allowed to omit it. gcc and clang both warn about this by default ("declaration does not declare anything") and reject it with -Wpedantic-errors.

(Anonymous structs and unions were added to the language in C11, and are discussed here, but the code in your question is not an anonymous struct.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631