c - 像 "char s[static 10]"这样的函数的数组参数中 static 关键字的用途是什么?

标签 c arrays parameters static

在浏览一些源代码时,我遇到了这样的函数:

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/

相关文章:

arrays - 从数组 Swift 3 中删除括号的第一部分

c++ - 在 C++ 中用字符串填充数组

javascript - Javascript 中是否可以为匿名调用函数提供参数计数?

clock() - c 函数的执行时间

c - 如何理解定义宏中的运算符 "\"?

javascript - 将数组中的所有对象合并为一个

java - 'void' 方法什么时候影响参数,什么时候影响原始对象?

parameters - 如何 JsDoc 为 "mixed"类型?

c - stub 特殊功能寄存器

c - 为什么我在使用 C 语言执行 execvp 时遇到困难?