C 参数数组声明符 [英] C Parameter Array Declarators

查看:25
本文介绍了C 参数数组声明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C99 中有变长数组,参数数组声明符中可以有静态限定符(和类型限定符):

In C99 there are variable-length arrays, and there can be static qualifiers (and type qualifiers) in parameter array declarators:

void f(int i, int *a);
void f(int i, int a[]);
void f(int i, int a[i]);
void f(int i, int a[*]);         // Only allowed in function prototypes.
void f(int i, int a[static i]);

由于数组函数参数只是简单地衰减为指针,所以之前的声明之间有什么实际区别,还是风格问题?什么时候应该使用它们中的任何一个?特别是,static 限定符意味着什么?该标准没有很好地阐明每种语法的原因.

Since array function parameters simply decay to pointers, is there any practical difference between the previous declarations, or is it a matter of style? When should any of them be used? In particular, what does the static qualifier imply? The standard does not render well clear the reason for each syntax.

推荐答案

只要您只处理一维数组,上述声明都是等价的.最后一个

As long as you are working with single-dimensional arrays only, the above declarations are all equivalent. The last one though

void f(int i, int a[static i])

有额外的效果.它在参数类型方面与前面的等效,但也告诉编译器它可以依赖 a 参数指向一个至少包含 i 个元素的数组(可用于优化).

has an extra effect. It is equivalent to the previous ones in terms of the parameter types, but also tells the compiler that it can rely on a parameter pointing to an array of at least i elements (which can be used in optimizations).

您还忘记了另一个新声明

You are also forgetting another new declaration

void f(int i, int a[const])

即使在一维数组的情况下,这个实际上也有效果.相当于

This one actually does have an effect even in case of a single-dimensional array. It is equivalent to

void f(int i, int *const a)

尽管有些人可能会争辩说,函数参数的 const 限定是无用的.在使用 [] 语法进行声明时,数组参数衰减"到无法对指针进行常量限定之前.

although some might argue that const-qualifications on function parameters are useless. Before it was impossible to const-qualify the pointer the array parameter "decays" to when using the [] syntax for the declaration.

[] 之间的 *(以及 i)只有在第二个(或更大的) 多维数组声明中的 [] 对.本质上,它就像一直以来一样:参数声明中的数组大小始终只在第二对或更多的[] 之间重要.* 用于 VLA 参数的原型声明中,当大小值未明确命名时.例如,您可以声明

The * (as well as i) between the [] begins to matter only when it is used between the second (or greater) pair of [] in multi-dimensional array declaration. In essence, it is just like it has always been: array size in the parameter declaration always mattered only between the second or further pair of []. The * is used in prototype declarations for VLA parameters, when the size value is not named explicitly. For example, you can declare

void bar(int n, int m, int a[n][m]);

并且编译器会知道 a 是一个 VLA,因为大小不是常数.但是,如果您不想在原型中命名参数,您将如何告诉编译器 a 是 VLA?这就是 * 帮助

and the compiler will know that a is a VLA since the sizes are not constants. But if you prefer not to name parameters in prototypes, how are you going to tell the compiler that a is a VLA? That's when * helps

void bar(int, int, int a[*][*]);

这篇关于C 参数数组声明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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