Study Guides/Computer Science/Difference Between Structure and Union in C
Study Guide ยท Computer Science

Difference Between Structure and Union (C Programming)

In C programming, arrays are great for storing multiple items, but they can only store items of the same data type (e.g., all integers). To group different data types together (like an integer ID, a float Salary, and a string Name), C provides two user-defined data types: Structures (struct) and Unions (union).

Question (Click to Flip)

Does C++ have structures and unions?

Answer

Yes, C++ fully supports both. However, in C++, a struct is basically identical to a class, except its members are public by default.

Card 1 of 1 free previews

Key Facts

Example calculation: A struct containing a char (1 byte), an int (4 bytes), and a double (8 bytes) will take 13 bytes of memory. A union with the same members will only take 8 bytes.

Changing the value of one member in a union will unpredictably alter the values of all other members.

1. What is a Structure (`struct`)?

  • Memory Allocation: A structure allocates distinct, separate memory space for every single variable inside it.
  • Total Size: The total memory size of a structure is the sum of the memory sizes of all its individual members.
  • Data Access: Because every variable has its own physical space, you can access, read, and write to all the variables simultaneously without any data getting corrupted.
  • Keyword: Defined using the keyword struct.

2. What is a Union (`union`)?

  • Memory Allocation: A union allocates only one shared memory block for all the variables inside it.
  • Total Size: The total memory size of a union is equal to the size of its largest member variable. (e.g., If it has an int (4 bytes) and a double (8 bytes), the total size of the union is just 8 bytes).
  • Data Access: Because all variables share the exact same physical memory location, you can only safely use one variable at a time. If you store a value in the integer, and then store a value in the double, the integer's data is instantly overwritten and destroyed.
  • Keyword: Defined using the keyword union.

3. Why use a Union?

You might wonder why anyone would use a Union if it destroys data. Unions are highly specialized. They are used in Embedded Systems programming (like microcontrollers in microwaves or cars) where RAM is extremely scarce (sometimes only 2 Kilobytes), and memory conservation is more important than holding multiple values simultaneously.

Questions and Answers

Does C++ have structures and unions?+

Yes, C++ fully supports both. However, in C++, a `struct` is basically identical to a `class`, except its members are public by default.

More in Computer Science

Study Smarter with Shinyu.ai

Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ€” free, no signup required.