Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array declared with static keyword: what is static, the pointer or the whole array?

Simple but tricky question:

void f() {
    static int a[3] = {1, 2, 3};
    ...

What is static here? The pointer to array or the whole array?

Can anybody point me to definition of that in the C standard?

Thanks!

like image 474
Silas Avatar asked Jan 13 '11 20:01

Silas


2 Answers

From the ISO C99 standard (section 6.2.1, "Scopes of identifiers"):

3 If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.22)

In your example it's the a identifier that becomes static (i.e. the symbol in the object file is not exported).

EDIT:

For non-file scope static declarations (section 6.2.4, "Storage durations of objects")

3 An object whose identifier is declared 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.

I take it this to mean that the array itself becomes static in this case, which makes sense, since the identifier would have invalid contents otherwise.

like image 143
thkala Avatar answered Sep 27 '22 17:09

thkala


It applies to the array. There is no pointer in your code. Array is not pointer.

#include <stdlib.h>
#include <stdio.h>

void f() {
    static int a[3] = {1, 2, 3};
        a[1]++;
        printf("%d\n", a[1]);
}

main()
{
        int i;
        for (i = 0; i < 5; i++)
        {
                f();
        }
}

outputs

3
4
5
6
7
like image 34
MK. Avatar answered Sep 27 '22 18:09

MK.