我对已接受的答案及其下面陈述相反内容的评论感到困惑 在 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 keywordstatic
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/