While browsing some source code I came across a function like this:
void someFunction(char someArray[static 100])
{
// do something cool here
}
With some experimentation it appears other qualifiers may appear there too:
void someFunction(char someArray[const])
{
// do something cool here
}
It appears that qualifiers are only allowed inside the [
]
when the array is declared as a parameter of a function. What do these do? Why is it different for function parameters?
The first declaration tells the compiler that someArray
is at least 100 elements long. This can be used for optimizations. For example, it also means that someArray
is never NULL
.
Note that the C Standard does not require the compiler to diagnose when a call to the function does not meet these requirements (i.e., it is silent undefined behaviour).
The second declaration simply declares someArray
(not someArray
's elements!) as const, i.e., you can not write someArray=someOtherArray
. It is the same as if the parameter were char * const someArray
.
This syntax is only usable within the innermost []
of an array declarator in a function parameter list; it would not make sense in other contexts.
The Standard text, which covers both of the above cases, is in C11 6.7.6.3/7 (was 6.7.5.3/7 in C99):
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the
[
and]
of the array type derivation. If the keyword static also appears within the[
and]
of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.