在浏览一些源代码时,我遇到了这样的函数:
void someFunction(char someArray[static 100])
{
// do something cool here
}
通过一些实验,似乎其他限定符也可能出现在那里:
void someFunction(char someArray[const])
{
// do something cool here
}
当数组被声明为函数的参数时,限定符似乎只允许在 [
]
内部使用。这些是做什么的?为什么函数参数不同?
最佳答案
第一个声明告诉编译器 someArray
的长度至少 100 个元素。这可以用于优化。例如,它还意味着 someArray
永远不会 NULL
。
请注意,C 标准不要求编译器在对函数的调用不满足这些要求时进行诊断(即,它是静默的未定义行为)。
第二个声明只是将 someArray
(不是 someArray
的元素!)声明为 const,即,您不能编写 someArray=someOtherArray
。这与参数为 char * const someArray
相同。
此语法只能在函数参数列表中数组声明符的最里面的 []
内使用;在其他情况下这没有意义。
涵盖上述两种情况的标准文本位于 C11 6.7.6.3/7 中(C99 中为 6.7.5.3/7):
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.
关于c - 像 "char s[static 10]"这样的函数的数组参数中 static 关键字的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225033/