Scope of Variables in C++2 min read

In any programming language, the scope is a region which is can be defined as the extent up to which something is valid. All the variables used in a program have their extent of use and if used out of that extent or boundary, they do not hold their values. Hence this boundary is referred to as the scope of a variable

These boundaries are referred to curly braces {} in a program. Based on their scope, there are two types of variables.

  • Local variables: inside a function or a block.
  • Global variables: outside of all functions.
  • Formal parameters: function parameters.
  • block: refers to anything between ‘{‘ and ‘}’.

1. Local variables:

Local variables are the variables that are declared within the body of the function or block. These types of variables can only be used within a block where it is created or declared, it has no existence outside the block.

Example: C++ example using local variables.

Output:

Let us see one more example where the variable with same name can be used in different function holding different values.

Output:


2. Global Variable

These variables are available to use throughout the program that is they have their scope throughout the program. They are defined outside the function (including main()), usually, you will see them at the top of any program.

After its declaration in a program, a global variable can be used inside any function present in a program.

Example: C++ example using global variables.

Output:

Let us see one more example where the local variable takes preference.

Output:

As you can see in the above program, g is declared global with a value of 20, but again it is initialized inside testFunction() with the value of 30. And present value(30) overrides the previous value (20) and prints 30.

In the main function again g is defined and initialized (making it local variable) with 50 that overrides the 20.


MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More