为什么可以在函数参数中指定数组的大小? [英] Why can one specify the size of an array in a function parameter?

查看:50
本文介绍了为什么可以在函数参数中指定数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么下面的例子可以编译和工作:

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]);

当然,在这种情况下,大小将成为编译时常量,并且不再传递length.

Of course, in this case the size will become a compile-time constant and there's no point of passing length anymore.

这篇关于为什么可以在函数参数中指定数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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