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 helps save memory when you only need one value 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 Number.Assign the integer value
42 to num.i.Assign the floating-point value
3.14f to num.f.Print the values of
num.i and num.f after each assignment.💡 Why This Matters
🌍 Real World
Unions are useful in low-level programming where memory is limited, such as embedded systems or device drivers.
💼 Career
Understanding unions helps in systems programming, working with hardware interfaces, and optimizing memory usage.
Progress0 / 4 steps