为什么一个可以指定一个函数参数数组的大小? [英] Why can one specify the size of an array in a function parameter?
问题描述
我不明白,为什么下面的例子编译和作品:
I don't understand why the following example compiles and works:
void printValues(int nums[3], int length) {
for(int i = 0; i < length; i++)
std::cout << nums[i] << " ";
std::cout << '\n';
}
似乎3的大小完全被忽略,但把一个无效的大小将导致编译错误。这到底是怎么回事呢?
It seems that the size of 3 is completely ignored but putting an invalid size results in a compile error. What is going on here?
推荐答案
在C ++(以及在C),与数组类型声明参数总是立即衰减到指针类型。以下三个声明是等价的。
In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent
void printValues(int nums[3], int length);
void printValues(int nums[], int length);
void printValues(int *nums, int length);
即。大小并不重要。然而,它仍然不意味着你可以使用一个无效的数组声明那里,即它是非法的指定负数或零大小,例如
I.e. the size does not matter. Yet, it still does not mean that you can use an invalid array declaration there, i.e. it is illegal to specify a negative or zero size, for example.
(顺便说一句,这同样适用于功能类型的参数 - 它立即衰减的指针到功能型)
(BTW, the same applies to parameters of function type - it immediately decays to pointer-to-function type.)
如果要强制参数和参数之间的数组大小匹配,使用指针 - 或者引用到阵列中的参数声明类型
If you want to enforce array size matching between arguments and parameters, use pointer- or reference-to-array types in parameter declarations
void printValues(int (&nums)[3]);
void printValues(int (*nums)[3]);
当然,在这种情况下,大小将成为一个编译时间常数,也没有传球点长度
了。
这篇关于为什么一个可以指定一个函数参数数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!