Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct behavior of the struct with unnamed member in C99 language?

#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;
}
like image 274
mezoni Avatar asked Feb 14 '15 14:02

mezoni


2 Answers

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.

like image 143
haccks Avatar answered Sep 28 '22 07:09

haccks


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.

like image 45
jschultz410 Avatar answered Sep 28 '22 07:09

jschultz410