在浏览一些源代码时,我遇到了这样一个函数:
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/3430315/