48

I’ve a bit confusion about static, auto, global and local variables.

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

However, I also know that a local variable also does the same, so what is the difference?

Jeff Widman
  • 22,014
  • 12
  • 72
  • 88
user1779646
  • 809
  • 1
  • 8
  • 21

6 Answers6

92

There are two separate concepts here:

  • scope, which determines where a name can be accessed, and
  • storage duration, which determines when a variable is created and destroyed.

Local variables (pedantically, variables with block scope) are only accessible within the block of code 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 file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:

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

(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)

Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.

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 static storage duration) 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. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 4
    thnks for answer, but i still cant get the diff between auto and local variable, isn't they both have storage duration of the running function, please clarify. – user1779646 Nov 16 '12 at 11:55
  • 20
    @user1779646: "automatic" means they have the *storage duration* of the current block, and are destroyed when leaving the block. "local" means they have the *scope* of the current block, and can't be accessed from outside the block. If a local variable is `static`, then it is not destroyed when leaving the block; it just becomes inaccessible until the block is reentered. See the `for`-loop examples in my answer for the difference between automatic and static storage duration for local variables. – Mike Seymour Nov 16 '12 at 11:58
  • @MikeSeymour Shoudn't That be termed as error as when for loop enter agains you are redefining `static int n = 0` – Suraj Jain Jul 26 '16 at 09:40
  • What i mean is when i create a program like this `static int y = 0 ;` `y = 1 ;` `printf("%d ", y );` `static int y = 0 ;` `printf("\n%d" , y)'` Then error `redefining y comes` .So when we enter a loop and `static int n = 0 ` and when we quit the loop because the storage is static it is not destroyed .So when we reenter the loop and line `static int n =0` comes shouldn't there be error – Suraj Jain Jul 26 '16 at 09:41
  • Also If there is no error then `static int n = 0` Then shouldn't it n becomes zero ??? I am really confused .? – Suraj Jain Jul 26 '16 at 09:47
  • @SurajJain That is an initialization, not an assignment. Static variables are initialized only once at declaration. – JakeD Dec 09 '18 at 18:32
12

First of all i say that you should google this as it is defined in detail in many places

Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.

Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.

/* 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 restricted by carefully placing the declaration. They are visible from the declaration 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:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list

AUTO:
C, C++

(Called automatic variables.)

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

Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.

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

Freak
  • 6,786
  • 5
  • 36
  • 54
  • 4
    How did you type so much in just 6 minutes ! – iammilind Nov 16 '12 at 11:12
  • 9
    Google finds plenty of bad information along with the good. Perhaps you could paste from a source that correctly describes local variables as having *block* scope, not *function* scope; and that global variables are also accessible outside functions as well as inside them (after making sure you have permission to copy and paste without attribution, of course). – Mike Seymour Nov 16 '12 at 12:13
  • 2
    "You should Google this" (implication: as opposed to looking on Stackoverflow) is starting to get both old and also turn into a grey area. I think many people don't realize SO *is* the result of Googling. – Emmel Nov 09 '16 at 21:41
5

Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.

For 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;
}
user1746468
  • 75
  • 2
  • 11
3

Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.

Additionally from your question, static variables can be declared locally in class or function scope and globally in namespace or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • then what about (auto variable) they too get deleted after function termination – user1779646 Nov 16 '12 at 11:12
  • `auto` variables (not to be confused with `auto` keyword) are typically non-static local variables. They are stored in what is usually called "stack" space. – iammilind Nov 16 '12 at 11:13
  • *"Local variables are non existent in the memory after the function termination"*, You probably mean ***Scope***, `{`,`}` and not function termination. – Alok Save Nov 16 '12 at 11:49
  • @Als, yes it's for scope. Here, I used the same wordings used in question. – iammilind Nov 16 '12 at 12:08
  • So global variables do not remain allocated in the memory throughout the life of the program irrespective of the function? – Akram Mohammed Jun 05 '20 at 01:14
  • 1
    @Akram, it's other way around. Global variables (`static` or `extern`) remain allocated throughout the lifetime of program. – iammilind Jun 05 '20 at 01:26
3

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

local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:

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

Sometimes this scoping is used on purpose with { } blocks:

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

global variables exist for the duration of the program.

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

Yuushi
  • 25,132
  • 7
  • 63
  • 81
2

When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer 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 goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()

Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -

Value of a = 1
Value of a = 1
Value of a = 1
  • We can also this phenomenon of static variables to count the number of objects created by using it in a constructor: – user3472599 Nov 25 '16 at 15:21