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/3430315/

相关文章:

c++ - 将包含主函数的 C 程序包装到 C++ 类中,

java - 迭代器 hasext 给出第二个值

swift - 我们可以在 SWIFT 中使用关键字作为参数名称吗?

Angular 2 : what is difference between resolve and data in routing paths?

c - LinkedList 将字符串输入节点并打印列表?

c - memcpy 上的段错误

python - 使用 setuid/setgid 包装器执行 Python 命令

java - 即使我将 1 个数组的值存储到另一个数组中并将它们作为一个整体打印,但数组仍然打印最后一个值

c++ - 如何将单链表变成双向链表

c# - Windows 上的应用程序以参数启动