Difference between static, auto, global and local variable in C++

C++ProgrammingObject Oriented Programming

There are two separate concepts here −

  • scope, which determines where a name can be accessed - global and local
  • storage duration, which determines when a variable is created and destroyed - static and auto

Scope

Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own.

Example

Live Demo

#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;
}

This will give the output −

Output

30

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.

Example

Live Demo

#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;
}

This will give the output −

Output

30

Storage duration

Automatic variables are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.

Example

for (int i =0 0; i < 5; ++i) {
   int n = 0;
   printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}

Static variables have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.

for (int i = 0; i < 5; ++i) {
   static int n = 0;
   printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}

Note that the static keyword has various meanings apart from static storage duration. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initializer.

raja
Published on 16-Feb-2018 10:49:49
Advertisements