Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Storage Classes in C++

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 544
    Comment on it

    Storage classes defines the scope of the variable in the function. Storage class specified for a variable shows that for how long time the variable will remain in the program and which section of the program will have the accessibility of the variable.
     
    It also determines the location of the variable.
     
    There are 5 storage classes used in C++ :-
     

    • auto
    • register  
    • static  
    • extern     

     
     
    1. auto- These variables are also known as local variables, it can only be used within the defined function. It dies after the execution of the function is finished.

    { 
    int mount; 
    auto int month;
     }

    In above example are of same class but auto can only be used within the function.

     

    2. register- It is also similar to the automatic storage duration. It also  works within the function. Instead of memory/RAM register variables are stored in the CPU registers for faster access.

    { 
    register int month;
     }

     

    3. static- Static storage class helps in making the local variable available for the life-time of the program instead of  a particular function. In C++ only one member of the class is shared by all objects.

    void month()
     {
     static int i = 10;
     i++; cout << i;
     } 
    int main() 
    { 
      month();      // Output = 11 
      month();      // Output = 12
      month();     // Output = 13
     }

    4. extern- Variable of extern storage class can be used globally. These variables have scope outside the function in which it is declared. In simple words global variable extern is used declare global variables in another function. For e.g two or more functions are sharing same global variables then extern is used.

    // external.cpp 
    // defined in another file 
    
    extern int another; 
    int main() { 
    int here; 
         { // refers to here in the enclosing scope extern int here; }
     }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: