Variable Scope in C++, Reference Variable in C++
Variable Scope in C++, Reference Variable in C++
C++
KALINGA INSTITUTE OF INDUSTRIAL
TECHNOLOGY
School Of Computer
Engineering
Local Variables
Variables that are declared inside a function or block are local variables.
They can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. Following is the example
using local variables −
local Variables
4
The C++ switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C++.
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
O/P: 30
Global Variables
5
Global Variables
Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function.
That is, a global variable is available for use throughout your entire program after its
declaration. Following is the example using global and local variables −
Example
6
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
local and global variables
7
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
References in C++
8
int main()
{
int y=10;
int &r = y; // r is a reference to int y
cout << r;
}
O/P: 10
here is no need to use the * to dereference a reference variable.
References in C++
9
#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x; O/P: x=20
// Value of x is now changed to 20 ref= 30
ref = 20;
cout << "x = " << x << endl ;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl ;
return 0;
}
Example (pass by reference)
10
#include <iostream>
using namespace std;
void swap(int& x, int& y) O/P:
{
Before Swap
a = 45 b = 35
int z = x;
After Swap with pass
x = y;
by reference
y = z;
a = 35 b = 45
}
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";
swap(a, b);
cout << "After Swap with pass by reference\n";
cout << "a = " << a << " b = " << b << "\n";
}
Reference variable Vs pointer variable
11