Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the static storage behaving differently in the two examples?

So here is an example:

#include <stdio.h>

int main(void) {
    static int i=0;
    printf("%d",i);
    static int i=0;
    printf("%d",i);
    return 0;
}

This gives me an error:
error: redefinition of 'i'

Now here is another Example :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
void increment(void) {
    static unsigned int counter = 0;
    counter++;
    printf("%d ", counter);
}

int main(void) {
    for (int i = 0; i < 5; i++) {
        increment();
    }
    return 0;
}

This gives the output :
1 2 3 4 5

Why does this happen ?
In the second example by calling the function aren’t we redeclaring it? And shouldn’t the output be 1 1 1 1 1 ?

>Solution :

In the second example by calling the function aren’t we redeclaring it?

No, we aren’t: We are declaring i in a different scope; specifically, in the body of a different function. You can only define a variable once within a given scope (ignoring sub-scopes); but you can define a variable of the same name in different scopes:

int i; // global scope

void foo()
{
    int i; // scope - body of foo
    {
        int i; // a sub-scope of the body of foo
    }
}

int main()
{
    int i; // a different scope - body of main, not body of foo
}

and the "closest" definition to a command is the one which will be relevant; it will "shadow" the other variables of the same name which might otherwise be usable in that scope.

Of course, it’s not a good idea to define many variables with the same name which may shadow each other – it’s confusing and their names will likely not be meaningful. People often use a one-letter variable for a loop counter: i, j, k etc. – but then you would tend avoid using i for something more long-lasting.

1 2 3 4 5
Why does this happen ?

Because within the increment() function, the counter is a static unsigned int, meaning it has static storage duration – it is only initialized once, and maintains its value between invocations of the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading