08 Feb Scope of Variables in C++
The existence of a variable in a region is called its scope, and the accessibility of a variable defines its scope. The scope of variables is of utmost importance when accessing variables. We will discuss the following:
- Local Variables, and
- Global Variables
Local Variables in C++
Whenever a variable is defined in a function or a block, it can be used only in that function or block. The value of that variable cannot be accessed from outside the function.
Let us see an example wherein we will create and initialize local variables. We will also see how to access and use local variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Local Variables in C++ #include <iostream> using namespace std; int main() { int p, q, r, s; p = 2; q = 5; r = 7; s = p * q * r; cout << "p = " << p; cout << "\nq = " << q; cout << "\nr = " << r; cout << "\ns (multiplication) = " << s; return 0; } |
Here is the output:
1 2 3 4 5 6 |
p = 2 q = 5 r = 7 s (multiplication) = 70 |
This C++ code initializes four local variables p, q, r, and s within the main function. It assigns values to p, q, and r, then calculates s as their product. The program prints the values of p, q, r, and s. These variables are only accessible within the main function, as they are local.
Global Variables in C++
A variable has global scope if it is defined outside a function, i.e., the code body, and is accessible from anywhere.
Let us see an example wherein we will learn how to create and work with global variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Global Variable in C++ #include <iostream> using namespace std; int s; // Global variable int main() { int p, q, r; p = 2; q = 5; r = 7; s = p * q * r; cout << "p = " << p; cout << "\nq = " << q; cout << "\nr = " << r; cout << "\ns (multiplication) = " << s; return 0; } |
Here is the output:
1 2 3 4 5 6 |
p = 2 q = 5 r = 7 s (multiplication) = 70 |
The above C++ code demonstrates the use of a global variable s. Inside the main function, it initializes three local variables p, q, and r with values 2, 5, and 7 respectively. The global variable s is set to the product of p, q, and r. The program then prints the values of p, q, r, and s.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments