[c++] Difference between static, auto, global and local variable in the context of c and c++

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?

This question is related to c++ c variables

The answer is


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.


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

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


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.


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

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?