Difference between static, automatic, global and local variable in c and C ++ context

I am a little confused in the variables static , auto , global and local .

I read somewhere that a static variable can only be obtained inside a function, but they still exist (remain in memory) after the function returns.

However, I also know that the local variable also does the same, so what's the difference?

+38
c ++ c variables
Nov 16 '12 at 11:05
source share
6 answers

There are two separate concepts here:

  • the area in which it is determined where the name can be accessed, and
  • storage duration, which determines when a variable is created and destroyed.

Local variables (pedantically, variables with a block area) are available only in the code block in which they are declared:

 void f() { int i; i = 1; // OK: in scope } void g() { i = 2; // Error: not in scope } 

Global variables (pedantically, variables with a file region (in C) or a namespace region (in C ++)) are available at any time after they are declared:

 int i; void f() { i = 1; // OK: in scope } void g() { i = 2; // OK: still in scope } 

(In C ++, the situation is more complicated, because namespaces can be closed and reopened, and areas other than the current one can be accessed, and names can also have a cool area, but this becomes very off topic.)

Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime expires when execution leaves the scope and is recreated when the region is re-entered.

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

Static variables (pedantically, variables with a static storage duration) have a lifespan that lasts until the end of the program. If they are local variables, then their value is preserved when the execution goes out of 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 has different meanings besides static storage duration. According to a global variable or function, it gives an internal connection so that it is not accessible from other translation units; on a member of a C ++ class, this means that there is one instance for each class, not one object. Also, in C ++, the auto keyword no longer means automatic storage duration; now this means the automatic type deduced from the variable initializer.

+79
Nov 16 '12 at 11:26
source share
β€” -

First of all, I say that you must do this Google, as it is defined in detail in many places

Local
These variables exist only within the specific function that creates them. They are unknown to other functions and the main program. Thus, they are usually implemented using the stack. Local variables cease to exist after the function that created them ends. They are recreated every time a function is executed or called.

Global
These variables can be accessed (i.e., known) by any function containing the program. They are implemented by associating memory locations with variable names. They are not recreated if the function is called.

 /* Demonstrating Global variables */ #include <stdio.h> int add_numbers( void ); /* ANSI function prototype */ /* These are global variables and can be accessed by functions from this point on */ int value1, value2, value3; int add_numbers( void ) { auto int result; result = value1 + value2 + value3; return result; } main() { auto int result; value1 = 10; value2 = 20; value3 = 30; result = add_numbers(); printf("The sum of %d + %d + %d is %d\n", value1, value2, value3, final_result); } Sample Program Output The sum of 10 + 20 + 30 is 60 

The scope of global variables can be limited by carefully placing ads. They are visible from the ad until the end of the current source file.

 #include <stdio.h> void no_access( void ); /* ANSI function prototype */ void all_access( void ); static int n2; /* n2 is known from this point onwards */ void no_access( void ) { n1 = 10; /* illegal, n1 not yet known */ n2 = 5; /* valid */ } static int n1; /* n1 is known from this point onwards */ void all_access( void ) { n1 = 10; /* valid */ n2 = 3; /* valid */ } 

Static:
A static object is an object that is saved from the moment of its creation to the end of the program. Thus, stack and heap objects are excluded. But global objects, objects in the namespace area, objects declared static inside classes / functions, and objects declared in the file area are included in static objects. Static objects are destroyed when the program stops working.
I suggest you look at this list of tutorials

AUTO:
C, C ++

(Called automatic variables.)

All variables declared in the code block are automatically by default, but this can be done explicitly with the auto keyword. [note 1] An uninitialized automatic variable has the value undefined until it is assigned a valid value of its type. [one]

Using a storage class register instead of auto is a hint for the compiler to cache a variable in the processor register. Besides the fact that the reference operator (&) is not used for a variable or any of its subcomponents, the compiler can ignore the hint.

In C ++, the constructor of automatic variables is called when execution reaches the declaration point. The destructor is called when it reaches the end of a given program block (program blocks are surrounded by curly braces). This feature is often used to control resource allocation and deallocation, such as opening and then automatically closing files or freeing memory. SEE WIKIPEDIA

+11
Nov 16 '12 at 11:11
source share

The difference is static variables - these are the variables that allow you to save the value from one function call to another. But in the case of local variables, the scope is up to the lifetime of the block / function.

Example:

 #include <stdio.h> void func() { static int x = 0; // x is initialized only once across three calls of func() printf("%d\n", x); // outputs the value of x x = x + 1; } int main(int argc, char * const argv[]) { func(); // prints 0 func(); // prints 1 func(); // prints 2 return 0; } 
+4
Nov 16 '12 at 11:18
source share

Local variables do not exist in memory after the function completes.
However, static variables remain allocated in memory throughout the entire program life cycle, regardless of any function.

In addition to your question, static variables can be declared locally in a class or in a function area and globally in a namespace or in a file area. They allocate memory from start to finish, it's just initialization, which happens sooner or later.

+3
Nov 16 '12 at 11:09
source share

static is a heavily overloaded word in C and C ++. static variables in the context of a function are variables that retain their values ​​between calls. They exist throughout the program.

local variables are stored only for the lifetime of the function or any of their covering areas. For example:

 void foo() { int i, j, k; //initialize, do stuff } //i, j, k fall out of scope, no longer exist 

Sometimes this goal definition is used with goals { } :

 { int i, j, k; //... } //i, j, k now out of scope 

there are global variables throughout the program.

auto now different from C and C ++. auto in C was a (superfluous) way of setting a local variable. In C ++ 11, auto now used to automatically get the value / expression type.

+3
Nov 16 '12 at 11:14
source share

When a variable is declared static inside a class, it becomes a common variable for all objects of this class, which means that this variable is more specific to any object. For example: -

 #include<iostream.h> #include<conio.h> class test { void fun() { static int a=0; a++; cout<<"Value of a = "<<a<<"\n"; } }; void main() { clrscr(); test obj1; test obj2; test obj3; obj1.fun(); obj2.fun(); obj3.fun(); getch(); } 

This program will generate the following output: -

 Value of a = 1 Value of a = 2 Value of a = 3 

The same applies to a static variable declared worldwide. The above code will generate the same result if we declare the variable as an external function void fun ()

If u removes the static keyword and declares a as a non-statistical local / global variable, then the output will be as follows: -

 Value of a = 1 Value of a = 1 Value of a = 1 
+2
Nov 25 '16 at 15:10
source share



All Articles