0
0
C++programming~20 mins

Scope of variables in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Scope of variables in C++
📖 Scenario: Imagine you are organizing a small event and need to keep track of the number of guests in different rooms. You will learn how variable scope works in C++ by using variables inside and outside blocks.
🎯 Goal: You will create variables with different scopes and see how their values change inside and outside blocks.
📋 What You'll Learn
Create a global variable
Create a local variable inside a block
Use a nested block with a variable of the same name
Print variable values to see which one is used
💡 Why This Matters
🌍 Real World
Understanding variable scope helps avoid bugs when multiple parts of a program use the same names.
💼 Career
Knowing scope is essential for writing clear, maintainable code in any programming job.
Progress0 / 4 steps
1
Create a global variable
Create a global integer variable called guests and set it to 10.
C++
Need a hint?

Global variables are declared outside any function.

2
Create a local variable inside main
Inside the main function, create a local integer variable called guests and set it to 5.
C++
Need a hint?

Local variables are declared inside functions and hide global variables with the same name.

3
Create a nested block with a new variable
Inside the main function, add a nested block using curly braces { }. Inside this block, create another integer variable called guests and set it to 2.
C++
Need a hint?

Variables declared in inner blocks hide variables with the same name in outer blocks.

4
Print variable values to see scope in action
Add std::cout statements to print the value of guests inside the nested block, inside main but outside the nested block, and outside main (use the global variable). Use std::cout and std::endl to print each value on its own line.
C++
Need a hint?

Use ::guests to access the global variable inside main.