Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are those strange array sizes [*] and [static] in C99?

Apparently the following function prototypes are valid in C99 and C11:

void foo(int a[const *]);  void bar(int a[static volatile 10]); 

What is the purpose of those strange subscript notations *, static, and CV qualifiers?

Do they help distinguish statically typed arrays from variable-length arrays? Or are they just syntactic sugar?

like image 297
Kerrek SB Avatar asked Jul 09 '13 22:07

Kerrek SB


People also ask

Can static array have variable size?

You cannot declare a static array of variable size because its space is allocated in the Data Segment (or bss segment in case of an uninitialized variable). Hence the compiler needs to know the size at the compile time and will complain if the size is not a constant.

What is a static array?

Static arrays have their size or length determined when the array is created and/or allocated. For this reason, they may also be referred to as fixed-length arrays or fixed arrays. Array values may be specified when the array is defined, or the array size may be defined without specifying array contents.

How are static arrays stored in memory?

Static arrays store their values on the stack, and their size must be known at compile time. This has major repercussions. If you want an array to be sized based on input from the user, then you cannot use static arrays. Dynamic arrays allow us to specify the size of an array at run-time.

Can we declare array with static keyword?

We can declare an array as a local variable or method parameter but, an array cannot be static.


1 Answers

static in parameter array declarator

 void f(int a[static 10]); 

static here is an indication that parameter a is a pointer to int but that the array objet (where a is a pointer to its first element) has at least 10 elements.

A compiler has then the right to assume f argument is not NULL and therefore it could perform some optimizations. gcc currently performs no optimization (source):

"The information provided by static in parameter array declarators is not used for optimization. It might make sense to use it in future in conjunction with work on prefetching."

qualifier in parameter array declarator

void g(int a[cvr 10]); 

inside g a is a cvr pointer to int (cvr is const, volatile or restrict qualifier). For example, with const it means a is a const pointer to int (i.e., type int * const).

So a parameter declaration:

T param[cvr e]  

is the same as a parameter declaration:

T * cvr param 

* in parameter array declarator

void h(int a[*]); 

The [*] in a formal array parameter declaration in a function declaration (that is not part of a function definition) indicates that the formal array is a variable length array.

like image 199
ouah Avatar answered Sep 21 '22 08:09

ouah