C++ Variable Scope





All the variables have their area of functioning, and out of that boundary they don't hold their value, this boundary is called scope of the variable. We will study the storage classes later, but as of now, we can broadly divide variables into two main types,

  1. Local Variable
  2. Global Variable

1. Local Variable

  • 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.

Example :

#include < iostream >
using namespace std;
int main()
{
 int i=10;
 if(i<20)        // if condition scope starts
  {
    int x=100;   // Local variable declared and initialized
  }              // if condition scope ends
 cout << x;      // Compile time error, x not available here
}                           
                    

2. Global Variable

  • Global variables are those, which are once declared and can be used throughout the lifetime of the program by any class or any function.

  • Global variables are defined outside of all the functions.

  • The global variables will hold their value throughout the life-time of your program.

Example :

#include < iostream >
using namespace std; 
// Global variable declaration:
int x; 
int main () {
   // Local variable declaration:
   int a, b;
   // actual initialization
   a = 10;
   b = 20;
   x = a + b; 
   cout << x; 
   return 0;
}
                        

Next topic is Constants / Literals in C++





 



Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved