Struct & Union
Struct & Union
{ name of the
data_type member1; structure
data_type member2: type of declaration for the
................. Member data items
}; that make up the
structure.
Example...
struct Book
{
char Name[100];
char Author[100];
char Publisher[80];
int Year;
int Pages;
float Price;
};
The keyword struct defines a book, and each line with
in the braces defines the elements of the Book. Now
when ever we create an instance of Book it will have all
the elements of the structure i.e. Name, Author,
Publisher , Year, Pages and Price.
Declaring a Structure
Now, we have only created the format of a structure,
but we still did not declare any variable which can
store value. Thus ,there is a need to declare structure
variable so that we can use the structure member in
the program.
There are two ways to declare structure variables:
1.structure variable declaration in structure template
2.structure variable declaration any where in the
program.
Syntax....
1. type..... 2.type.......
Struct structure_ name struct structure_ name
{ {
data_type member1; data_type member1;
data_type member2; data_type member2;
................ ................
}var1,var2,......; ................
};
struct structure_ name
;
var1,var2,........;
Initializing a Structure
Initialization in structure Initialization out of structure
template template
{ {
char title [15]; char title[15];
char author[10]; char author[10];
int pages; int pages;
float price; float price;
}b1={“let us c,” };
”kanetkar”,300,50.25}; struct book b1={“let us c” ,
“kanetkar” ,300,50.25};
Continue....
if there are fewer initializations than that of
member variables in the structure the
remaining member variables are initialized to
zero.