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 s开发者_如何学Pythontandard?
Thanks!
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.
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
In code:
static int a[3] = {1, 2, 3};
Type for a is not pointer, but array of int. However, it is automatically converted into pointer, e.g. in C standard:
Except when it is the operand of the sizeof operator or the unary & operator,or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
So if a is array, than = { 1, 2, 3 } is it's initialization, not some kind of separate array. I don't know if it's specified exactly somewhere, but in this sense it is used throughout the standard.
Edit to clear up confusion by some of readers: according to cited 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
精彩评论