Structure And Union

46 views

Structure 

A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.

A structure is combination of different data types. Structs are generally useful whenever a lot of data needs to be grouped together–for instance, they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct could be used that would hold all of the information about a single contact–name, address, phone number, and so forth.

Syntax:
struct Tag {
Members
};
struct Tag name_of_single_structure;

main()
{
name_of_single_structure.name_of_variable;
}

Example:

struct emp{
int id_number;
int age;
float salary;
};

int main()
{
emp employee; //There is now an employee variable that has modifiable
// variables inside it.
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}

Union 

A union is an object similar to a structure except that all of its members start at the same location in memory. A union can contain the value of only one of its members at a time. The default initializer for a union with static storage is the default for the first component; a union with automatic storage has none.

#include
#include

union {
  char birthday[9];
  int age;
  float weight;
} people;

int main(void) {
  strcpy(people.birthday, “03/06/56″);
  printf(”%s\n”, people.birthday);
  people.age = 38;
  printf(”%s\n”, people.birthday);
}

Output :

03/06/56
&



« Lesson 5. Conditional Statements Enumerated Type - enum »
Posted on Monday, June 23rd, 2008 at 5:00 pm under C For Beginners | RSS 2.0 Feed

Post Comment

You must be logged in to post a comment.



ComputerEducationWorld.com All Rights Reserved © RSS | CBSE | Education Boards Of India | What is My IP?