Structure

  • Structure / struct is a user-defined data type that enables us to organize and group together variables of the same or different data types under a single unit for the purpose of creating composite data structures.
  • We studied in our pervious tutorial about arrays. They hold data with the same data type.

Why do we need struct?

What if we need to store more than one variables with same or different data types? Store name, registration number and marks of students? In arrays, we store only marks of students. But if want to store name and registration number along with marks, we use structures or struct. And variables in structures are called members of that particular struct.

Note: We declare struct outside the main function.

  • Arrays: Collection of data values with same data type.
  • Struct: Collection of data values with same or different data type.

Accessing members of struct

We have to create an instance of struct inside main function and then using "." operator, we can access members of struct.

Modifying members of struct

We can reassign data values to our struct members.

Note: Actually structures make your code more readable, and it makes code easy to manage.

Size of struct

  • Size of struct depends upon the type of variable and number of variables, it is storing.
  • If struct has 1 int (4 bytes), 1 char(1 byte) and 1 float(4 bytes), its size would be 9 bytes. You can check it by using sizeof() operator.

Unions

Syntax of union is same as struct. We use union when we need only one data member at a time. For example, if we have three books, we can read one book at a time. We can use one data member of union at a time.

Note: You can not declare functions inside a union.

We can declare union and use its one data member at a time. Unions provide us memory optimization.

If we declare a union and a struct with same data members, memory taken by union will be less.

Size of Union

In this case, size of union will be 4 bytes.

Points: Do not forget to put ";" after declaring struct or union.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min