Scope of Variable

Let's classify variables according to their accessibility in the program.

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 can only be accessed within the block in which it is declared.


A block can be a function, loop, or conditional statement. These variables are created when the compiler executes that particular block and destroyed when the compiler exits that block.

Illustration

See the illustration given below!

Get hands-on with 1400+ tech skills courses.