0
0
Cprogramming~20 mins

Union basics - 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 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
1
Create the union and variable
Write a union named Number with two members: int i and float f. Then create a variable called num of type union Number.
C
Need a hint?

Use the union keyword to define the union. Inside, declare int i; and float f;. Then declare a variable num of this union type.

2
Assign an integer value
Assign the integer value 42 to the member num.i.
C
Need a hint?

Use the dot operator to assign 42 to num.i.

3
Assign a float value
Assign the float value 3.14f to the member num.f.
C
Need a hint?

Use the dot operator to assign 3.14f to num.f.

4
Print the values
Print the values of num.i and num.f using printf. Use %d for the integer and %f for the float. Print num.i first, then num.f on the next line.
C
Need a hint?

Use printf("%d\n", num.i); to print the integer and printf("%f\n", num.f); to print the float. Remember to include stdio.h and write a main function.