32

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?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084

1 Answers1

28

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 2
    How is this useful? I don't seem to get *any* meaningful diagnostics when I call the functions with the wrong type of array (wrong size or wrong VLAness). Do you get `sizeof` support for `[*]`? – Kerrek SB Jul 09 '13 at 23:01
  • @KerrekSB C does not require the diagnostic and I guess compilers are not giving a warning because this feature is so rarely used. – ouah Jul 09 '13 at 23:05
  • @KerrekSB for `sizeof` with `int (*)[*]` for example with `gcc` I get *‘[\*]’ not allowed in other than function prototype scope* – ouah Jul 09 '13 at 23:11
  • 3
    @KerrekSB, `sizeof` for the `[*]` is not possible for the simple reason that this is **only** allowed in declarations and not in definitions. For VLA as function parameters the size expression is evaluated as if it where placed at the beginning of the function body. `[*]` is a placeholder for the expression in the declaration for those case where one doesn't know (or doesn't want) to make that expression visible in the interface. Inside the function `sizeof` works as expected, only that you don't have the first dimension, as always for array parameters. – Jens Gustedt Jul 10 '13 at 06:24