什么是static关键字的像&QUOT功能数组参数的目的;个char [静态10"? [英] What is the purpose of static keyword in array parameter of function like "char s[static 10]"?

查看:109
本文介绍了什么是static关键字的像&QUOT功能数组参数的目的;个char [静态10"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览部分源$ C ​​$ C我碰到一个函数来是这样的:

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 为const,(不是的someArray 的元素!),即你可以不写 =的someArray someOtherArray 。这是一样的,如果该参数是字符(*常量的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也出现在 [] 数组类型派生的,则每次调用函数,相应的实际参数的值应提供访问数组的第一个元素至少有尽可能多的
  由大小前pression指定的元素。

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.

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

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