Website For Developers

Scope of variables in C++



In C++, scope refers to (within) the scope of the identifier/variable can be accessed.


Local variables in C++


Example of local variables in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  // Local variables declaration
  int a,b;
  // Local variables initialization
  a = 10;
  b = 15;
  cout<<a<<endl<<b;
  getch();
  return 0;
}

Output

10
15


Global variables in C++


Example of global variables in C++

#include<iostream>
#include<conio.h>
using namespace std;
// Global variable declaration and initialization
int a = 50;
int main() {
  cout<<"Value of a = "<<b<<endl;
  getch();
  return 0;
}

Output

50