c++ - C/C++ 中将数组作为形式参数传递为 int arr[] 和 int arr[N] 之间的区别

标签 c++ c arrays

我对已接受的答案及其下面陈述相反内容的评论感到困惑 在 Passing Arrays to Function in C++ .

作为函数的形式参数将数组作为 int arr[]int arr[N] 传递有什么区别吗?换句话说,void foo(int arr[])void foo(int arr[N]) 之间有区别吗?

最佳答案

void foo(int arr[])void foo(int arr[N]) 完全相同。这是因为作为函数参数的数组被调整为指针。所以以上两者都翻译为:

void foo(int *arr)

这在 C standard 的第 6.7.6.3p7 节中指定关于“函数声明符”:

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.

类似的语言存在于 C++ standard 的 11.3.5p5 节中。 :

A single name can be used for several different functions in a single scope; this is function overloading(Clause 16). All declarations for a function shall agree exactly in both the return type and the parameter-type-list. The type of a function is determined using the following rules. The type of each parameter (including function parameter packs) is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”. After producing the list of parameter types, any top-leve lcv-qualifiers modifying a parameter type are deleted when forming the function type. The resulting list of transformed parameter types and the presence or absence of the ellipsis or a function parameter pack is the function’s parameter-type-list.[Note:This transformation does not affect the types of the parameters.

关于c++ - C/C++ 中将数组作为形式参数传递为 int arr[] 和 int arr[N] 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491657/

相关文章:

c - 这个指令是什么意思(subl $20,%esp)?

c - 使用 setitimer() 和 ITIMER_VIRTUAL 时,是什么导致虚拟运行时间变慢?

c++ - 在其他模块中通过 cPar 更改模型参数

c - 每次我使用 fopen 时调试断言表达式流!=null

C++11 线程分离

c++ - 为什么我的代码给我一个分段/核心转储错误?

javascript - 如何检查 Javascript 对象是否包含数组作为属性值?

arrays - 数组中每个项目之前有多少个连续元素较小

C++:是否会隐式复制结构

c++ - 当包含对象包含 unique_ptr 时如何删除 vector 的元素?