Search code examples
c++cstaticautostorage-class-specifier

Confusion related to auto and static variables


#include<stdio.h>
int main(){
    int a=10;
    {    printf("%d",a);
         int a=20;
         printf("%d",a);
    }
    printf(" %d",a);
    return 0;
}

Output:10 20 10

In the above code I understand that the visibility of variable a(inside inner block) has scope only within that block therefore I get that particular output. But the variable a which is declared outside that block should have its scope even within the inner block...Therefore how is it possible for me to again type int a=20; Shouldn't it give me an error like "redefinition of a" and "previous declaration of a was here". Like if I use

int b=10;
int b=15;

My second problem is this

void main() {
 static int a=10;

    {
         printf("%d ",a);
         static int a=20;
         printf("%d",a);
    }
    printf(" %d",a);

}

Apart from the same doubt as the previous code about why I'm not getting an error like "redefinition of a", This is my doubt related to this code.

For the above code i get the same Output: 10 20 10 but what I was expecting was

10 20 20 

I mean in the inner block once static int a is reinitialized to 20 shouldn't it be the same value even after it exits the block? because the a static variable's scope is throughout the entire program.


Solution

  • Answer for the first problem: It is called variable shadowing. From Wikipedia:

    variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.

    Simply put, when you create a variable with the same name but in other scope it shadows the previous variable.

    About the second problem - here is a fine example:

    // static1.cpp
    // compile with: /EHsc
    #include <iostream>
    
    using namespace std;
    void showstat( int curr ) {
       static int nStatic;    // Value of nStatic is retained
                              // between each function call
       nStatic += curr;
       cout << "nStatic is " << nStatic << endl;
    }
    
    int main() {
       for ( int i = 0; i < 5; i++ )
          showstat( i );
    }
    

    Output:

    nStatic is 0

    nStatic is 1

    nStatic is 3

    nStatic is 6

    nStatic is 10