Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c - What is the purpose of static keyword in array parameter of function like "char s[static 10]"?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...