Its been a while that I am not in touch with the C language, so I was just going through some of the concepts but could not find any good source on structures.
Can anyone please explain
struct A
{
int a;
char b;
float c;
};
Is this the declaration or the definition of the structure A
.
It declares a struct with the struct tag A
and the specified members. It does neither define nor reserve any storage for an object.
From the C99 Standard, 6.7 Declarations:
Semantics
5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
— for an object, causes storage to be reserved for that object;
— for a function, includes the function body; (footnote 98)
— for an enumeration constant or typedef name, is the (only) declaration of the identifier.
For a definition, you would need to provide an object identifier before the final semicolon:
struct A
{
int a;
char b;
float c;
} mystruct;
To also initialize mystruct you would write
struct A
{
int a;
char b;
float c;
} mystruct = { 42, 'x', 3.14 };
It is a declaration.
struct A;
is a forward declaration or incomplete declaration.
struct A
{
int a;
char b;
float c;
};
is complete struct
declaration.
Example
Also check comp.lang.c FAQ list Question 11.5
After forward declaration of struct
, you can use structure pointers but can not dereference the pointers or use sizeof
operator or create instances of the struct
.
After declaration, you can also use struct
objects, apply the sizeof
operator etc.
From 6.7.2.1 Structure and union specifiers from C11 specs
8 The type is incomplete until immediately after the } that terminates the list, and complete thereafter.
And from 6.7.2.3 Tags
If a type specifier of the form
struct-or-union identifier occurs other than as part of one of the above forms, and no other declaration of the identifier as a tag is visible, then it declares an incomplete structure or union type, and declares the identifier as the tag of that type.131)
131A similar construction with enum does not exist
This should not be confused with extern struct A aa;
v/s struct A aa ={/*Some values*/};
which are declaration and definitions of object aa
.
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