Scope of Variable
Explore the concept of variable scope in C++. Learn to differentiate between local and global variables, understand where each type is accessible within your code, and see examples demonstrating their behavior in functions and blocks. This lesson helps you manage variable accessibility effectively in your C++ programs.
Introduction
The scope of a variable defines which part of the program that particular variable is accessible in. In C++, the variable can be either of these two:
- Local variable
- Global variable
Local variable
Suppose you are staying at a hotel. The hotel manager gives you a key to room No. 5. You can only access room No. 5 in the hotel.
The local variable is just like a hotel room-specific key. It is only accessible within the block in which it is declared.
📝 Block is a section of code enclosed inside the curly braces.
The local variable ...