#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?
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.
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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With