E-learning

Computer-Based Training (CBT) or Internet-Based Training (IBT) or Web-Based Training (WBT) courses at BengalStudents website

Question and Answer

Q What are the differences between a union and a structure?

A Basically, the difference between a union and a structure is that the members in a union are overlaid and they share the same memory location, whereas the members in a structure have their own memory locations. A union can be referenced by using one of its member names.

Q What will happen if you initialize all members of a union together?

Using Unions

Using Unions

Now let’s focus on the applications of unions. Basically, there are two kinds of union applications, which are introduced in the following two sections.
Referencing the Same Memory Location Differently

The first application of unions is to reference the same memory location with different union members.

Unions Versus Structures

Unions Versus Structures

You might notice that in Listing 20.1, I assigned a value to one member of the dish union, and then immediately printed out the assigned value before I moved to the next union member. In other words, I didn’t assign values to all the union members together before I printed out each assigned value from each member in the union.

What Is a Union?

What Is a Union?

A union is a block of memory that is used to hold data items of different types. In C, a union is similar to a structure, except that data items saved in the union are overlaid in order to share the same memory location. More details on the differences between unions and structures are discussed in the following sections.
Declaring Unions

The syntax for declaring a union is similar to the syntax for a structure. The following is an example of a union declaration:

Exercises : Answer the following Question

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix E, “Answers to Quiz Questions and Exercises.”

What’s wrong with the following structure declaration?

struct automobile {
int year;
char model[8];
int engine_power;
float weight;
}