What is the correct behavior of a structure with an unnamed member in C99?

#include <stdio.h> struct s {int;}; int main() { printf("Size of 'struct s': %i\n", sizeof(struct s)); return 0; } 

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

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

The 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 is a full type and cannot be overridden.
Does this mean that the full type can have zero size?

Also, what does a declaration does not declare anything mean if this declaration declares a complete structure?

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

 #include <stdio.h> struct s {int;}; struct S { struct ss; // <=========== No problem to use it }; int main() { printf("Size of 'struct s': %i\n", sizeof(struct s)); return 0; } 
+6
source share
2 answers

Undefined behavior according to C.

J.2 undefined behavior:

Undefined behavior in the following cases:
....
- The structure or association is determined without any named members (including those indicated indirectly through anonymous structures and associations) (6.7.2.1).

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

 struct empty { }; 

The structure is zero size.

This makes the above program specific to the compiler.

+7
source

A type with size 0 is not standard. This is the gcc extension.

If you add -pedantic-errors to your gcc-compiling line, it will not compile.

+2
source

Source: https://habr.com/ru/post/982490/


All Articles