Structure
- Structure / struct is a user-defined data type that allow you to group together variables of different data types under a single name.
- We define a structure by using the struct keyword followed by the structure name and a pair of curly braces containing the member variables.
- Variables in a struct are called the members of 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
Multiple Instances of Struct
We can make as many struct type variables as we want. As struct is a data type, therefore, like any other data type, it can have multiple instances.
Changing values of Structure
Like any other assigned value, we can also reassign the value of struct.
Unions
- A union is a composite data type that allows you to store different types of data in the same memory location. Unlike structures, which allocate memory for all of their members separately, unions allocate memory only for the largest member, and all members share the same memory location.
- We use only one member of structure at a time.
Note: You can not declare functions inside a union.
We can declare struct 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.
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