An array declared with the static keyword: what is static, a pointer, or the entire array?

A simple but complicated question:

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

What is static here? Pointer to an array or the entire array?

Can someone point me to a definition of what's in the C standard?

Thanks!

+6
c arrays pointers static
source share
3 answers

From the ISO C99 standard (section 6.2.1, “Identifier areas”):

3 If the declaration of the content area of ​​an object or function identifier contains a storage class specifier static, the identifier has an internal relationship .22)

In your example, this is identifier a , which becomes static (i.e. the character in the object file is not exported).

EDIT:

For static declarations of the non-file domain (section 6.2.4, “Duration of storage of objects”)

3 An object whose identifier is declared with external or internal communication or with the static static storage class has a static storage duration. Its service life is the entire execution of the program and its stored value is initialized only once, before the program starts.

I assume that this means that the array itself becomes static in this case, which makes sense, because otherwise the identifier would have invalid content.

+6
source share

In code:

 static int a[3] = {1, 2, 3}; 

The type for a is not a pointer, but an array from int. However, it is automatically converted to a pointer, for example. in standard C:

Unless it is an operand of the sizeof operator or a unary operator & or a string literal used to initialize an array, an expression that is of type `` an array of type is converted to an expression with a pointer of type '' to indicate that it points to the initial element of an array object and is not an lvalue.

So, if a is an array, then = {1, 2, 3} is initialization, not some kind of separate array. I do not know whether it is specified somewhere exactly, but in this sense it is used throughout the standard.

Modify to eliminate confusion by some readers: according to the quoted standard, if you write:

 int arr[4] = { }; arr[0] = 1; //arr here has here type int* size_t sz = sizeof(arr); //here it is not type int*, sizeof is exception 
+2
source share

This refers to an array. The code is missing a pointer. An array is not a 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(); } } 

exits

 3 4 5 6 7 
+2
source share

All Articles