Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between struct S { int align; }; (name after struct keyword) and struct { int align; } S; (name after the struct definition)

#include <stdio.h>

struct Header
{
    unsigned long long int alignment;
};

int main(void)
{
    struct Header header;  // note: we can loose the 'struct' in C++
    struct Header* pheader = &header;

    return 0;
}

The program above compiles perfectly in both C and C++.

But when i change the Header struct to:

struct {
    unsigned long long int alignment;
} Header;

it fails with the following message in C: error: storage size of ‘Header’ isn’t known

and in C++: error: aggregate ‘main()::Header header’ has incomplete type and cannot be defined struct Header header;

A similar structure is used in the implementation of the Storage Allocator in the C programming Language book by K&R. I thought it was the same thing, but I learn that it isn't. I have since seen in other places as well. I am of course more familiar with the first version. What does the second one mean and why does it even exist? What is the difference?

like image 710
KeyC0de Avatar asked Oct 25 '18 02:10

KeyC0de


2 Answers

struct Header {}; introduces a struct type named Header.

typedef struct {} Header; introduces an anonymous struct type, and an alias Header for that anonymous type.

struct {} Header; introduces both an anonymous struct type, and a variable named Header of the anonymous type.

When there is no type named Header (the last case), struct Header header; introduces a struct type named Header without a body, then tries to create a variable header of that type.

like image 150
Yakk - Adam Nevraumont Avatar answered Oct 20 '22 01:10

Yakk - Adam Nevraumont


When you are compiling below portion

struct {
    unsigned long long int alignment;
} Header;

struct has no tag, it's called anonymous structure type. while doing

struct Header header;

compiler produces an error like

Header header’ has incomplete type and cannot be defined struct Header header

Hence in these cases it's better to typedef the struct. For e.g

typedef struct {
    unsigned long long int alignment;
} Header;
like image 45
Achal Avatar answered Oct 20 '22 01:10

Achal