Union basics
📖 Scenario: Imagine you want to store either an integer or a floating-point number in the same place in memory, but never both at the same time. This is useful when you want to save memory and know that only one type will be used at a time.
🎯 Goal: You will create a union in C that can hold either an int or a float. Then you will assign values and print them to see how unions work.
📋 What You'll Learn
Create a union named
Number with two members: int i and float f.Create a variable
num of type union Number.Assign an integer value to
num.i and print it.Assign a float value to
num.f and print it.Observe how the union shares memory for both members.
💡 Why This Matters
🌍 Real World
Unions are used in low-level programming, such as embedded systems, where memory is limited and you want to store different types of data in the same space.
💼 Career
Understanding unions is important for systems programming, device driver development, and working with hardware interfaces where efficient memory use is critical.
Progress0 / 4 steps