6
votes
#include <stdio.h>

struct s {int;};

int main()
{
    printf("Size of 'struct s': %i\n", sizeof(struct s));    
    return 0;
}

Microsoft C compiler (cl.exe) does not want compile this code.

error C2208: 'int' : no members defined using this type

GNU C compiler (gcc -std=c99) compiles this code...

warning: declaration does not declare anything

...and displays the result:

Size of 'struct s': 0

This means that struct s in gcc are complete type and cannot be redefined.
Does this means that the complete type can have zero size?

Also, what means the message declaration does not declare anything if this declaration declares the complete struct?

Here is the proof that the struct s is a complete type in (gcc -std=c99).

#include <stdio.h>

struct s {int;};

struct S {
    struct s s; // <=========== No problem to use it
};

int main()
{
    printf("Size of 'struct s': %i\n", sizeof(struct s));

    return 0;
}
2
I think it is a feature of gcc, but not a feature of c99VolAnd
@VolAnd. Thanks. This is because for me is not understandable the term undefined behavior in language specifctions. Undefined behavior at runtime or undefined behavior at compile time.mezoni
"warning: declaration does not declare anything" is about compile time. Undefined behavior is about runtime.VolAnd
@VolAnd Er, no. Undefined behavior just means the standard imposes no requirements.user3920237
I'm agree, it is impossible to write requirements for incorrect usage of language. But for me, personally, "undefined behavior" is rather about programs written as "bad programming examples" than about compilers that do anything with "bad programming examples"VolAnd

2 Answers

7
votes

The behavior is undefined as per C standard.

J.2 Undefined behavior:

The behavior is undefined in the following circumstances:
....
A structure or union is defined without any named members (including those specified indirectly via anonymous structures and unions) (6.7.2.1).

struct s {int;}; is equivalent to struct s {}; (no members) and GCC allows this as an extension.

struct empty {

};

The structure has size zero.

This makes the above program a compiler specific.

2
votes

A type with size 0 is not standard. That is a gcc extension.

If you add -pedantic-errors to your gcc compile line, then it won't compile.