0
0
C++programming~15 mins

Union basics in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the union Number
Write a union named Number with two members: an int called i and a float called f.
C++
Need a hint?

A union is like a struct but shares memory for all members. Use the keyword union followed by the name and curly braces.

2
Create a variable num of type Number
Declare a variable named num of type Number.
C++
Need a hint?

To create a variable of a union type, write the union name followed by the variable name and a semicolon.

3
Assign integer and float values to num
Assign the integer value 42 to num.i. Then assign the floating-point value 3.14f to num.f.
C++
Need a hint?

Use the dot operator to access union members and assign values like num.i = 42;.

4
Print the values of num.i and num.f
Print the values of num.i and num.f after the assignments using std::cout. Print num.i after assigning 42, then print num.f after assigning 3.14f.
C++
Need a hint?

Use std::cout to print text and values. Remember to include <iostream> and use std::endl for new lines.