Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure Confusion

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.

like image 864
Rohit Saluja Avatar asked Feb 27 '15 09:02

Rohit Saluja


2 Answers

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 };
like image 85
Jens Avatar answered Oct 13 '22 13:10

Jens


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.

like image 22
Mohit Jain Avatar answered Oct 13 '22 14:10

Mohit Jain