sun qingyao February 2016

Why doesn't `bar` in this code have static storage duration?

Code goes first:

#include <stdio.h>

void foo()
{
        static int bar;
}

int main()
{
        bar++;
        return 0;
}

The compiler(Clang) complains:

static.c:10:2: error: use of undeclared identifier 'bar'

Shouldn't the statement static int bar; in foo() give bar static storage duration, which makes it declared and initialized prior to main function?

Answers


David Hoelzer February 2016

Marking something as static within a function relocates its storage off of the stack and allows its value to persist across multiple calls.

Marking something static, however, does nothing to change the scope of the variable. While you certainly could create a pointer that is aimed at bar and manipulate it from main, the compiler will view bar as undefined within main because of scoping.


Sourav Ghosh February 2016

You are confusing the scope of a variable with the storage duration.

As mentioned in the C11 standard, chapter ยง6.2.1, Scopes of identifiers,

  • for file scope

[...] If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. [...]

and for function (or block) scope

[...] If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. [...]

In your case, bar has the file scope in foo(). So this is not visible in main().

OTOH, for the storage duration part,

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

So, to summarize, bar has static storage duration, but the scope is limited to the foo() function. So, it is

declared and initialized prior to main() function

(before main() starts, to be exact) but not visible and accessible in main().

Post Status

Asked in February 2016
Viewed 1,416 times
Voted 11
Answered 2 times

Search




Leave an answer