There are two separate concepts here −
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.
#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 −
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.
#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 −
30
Automatic variables are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
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.