What is a Union?

A union is a user defined variable which may hold members of different sizes and type. Union uses a single memory location to hold more than one variable. We can use the unions in the following locations.

  1. Share a single memory location for a variable myVar1 and use the same location for myVar2 of different data type when myVar1 is not required any more.
  2. Use it if you want to user, for example, a long variable as two short type variables.
  3. We don’t know what type of data is to be passed to a function, and you pass union which contains all the possible data types.

Defining a Union

Union can be defined by the keyword union.

Here we have defined a union with the name myUnion and it has two members i.e. var1 of type int and var2 of type long

Declaring the Union

We can declare the union in various ways. By taking the above example we can declare the above defined union as.

So newUnion will be the variable of type myUnion. We can also declare the union as

Initializing the Union

We can initialize the union in various ways. For example

or we can initialize it as

In later stages we can also initialize the var2 as well but this will over write the var1 value. Normally when we declare the union it is allocated the memory that its biggest member can occupy. So here in our example newUnion will occupy the memory which a long type variable can occupy.

What is a Structure

A structure is a convenient tool for handling a group of logically related data items. Structure help to organize complex data is a more meaningful way. It is powerful concept that we may after need to use in our program Design.

A structure is combination of different data types. Lets take the example of a book, if we cant to declare a book we will be thinking about the name, title, authors and publisher of the book and publishing year. So to declare a book we need to have some complex data type which can deal with more than one data types. Lets declare a Book.

Defining a Structure

We can declare a structure to accommodate the book.

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 and Year.

Declaring a Structure

We can declare the structure just like union.

Initializing a Structure

Lets initialize the structure variable CProgrammingBook.

Accessing the members of a Structure

We can access all the members of a structure by adding a period after the name of the structure variable name and then the name of the field we want to access. For example we want to change the Publish year from 2001 to 2002, we will do
it as