像“char s[static 10]"这样的函数的数组参数中静态关键字的目的是什么? [英] What is the purpose of static keyword in array parameter of function like "char s[static 10]"?

查看:20
本文介绍了像“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?

推荐答案

第一个声明告诉编译器 someArray 至少 100 个元素长.这可以用于优化.例如,这也意味着 someArray 永远不是 NULL.

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.

请注意,C 标准不要求编译器在对函数的调用不满足这些要求时进行诊断(即,它是无声的未定义行为).

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).

第二个声明简单地将someArray(不是someArray的元素!)声明为const,即你不能写someArray=someOtherArray.就像参数是 char * const someArray 一样.

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.

涵盖上述两种情况的标准文本位于 C11 6.7.6.3/7(在 C99 中为 6.7.5.3/7):

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):

将参数声明为类型数组"应调整为指向类型的限定指针",其中类型限定符(如果有)是在 [ 中指定的那些和 ] 的数组类型推导.如果关键字static 也出现在数组类型派生的[] 中,那么对于函数的每次调用,对应的实参的值应提供对至少具有相同数量的数组的第一个元素由大小表达式指定的元素.

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.

这篇关于像“char s[static 10]"这样的函数的数组参数中静态关键字的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆