pm1*_*100 -1 c c++ language-lawyer
我以为
int a1[5];
Run Code Online (Sandbox Code Playgroud)
和
int a2[6];
Run Code Online (Sandbox Code Playgroud)
是不同的类型。
但
void foo(int a[5]){};
void foo(int a[6]){};
Run Code Online (Sandbox Code Playgroud)
不会编译,说它们是 foo 的重复定义(即foo(int *a))
我对此感到非常惊讶。我看到 C++ 标准中不允许 VLA 的原因之一是它们破坏了类型系统。
我也惊讶地发现 c 也在做同样的事情。
void foo(int a[4]){
printf("sz=%ld", sizeof(a));
}
Run Code Online (Sandbox Code Playgroud)
报告指针大小。我期望它报告4*sizeof(int)(并且只接受类型变量int[4]作为调用参数)
是的,它们是不同的类型,这可以通过以下方式确认:
int a[5];
int b[6];
static_assert(!std::is_same_v<decltype(a), decltype(b)>);
Run Code Online (Sandbox Code Playgroud)
您的问题是,在函数参数列表中,数组会默默地替换为指针,因此void foo(int a[5])和void foo(int a[6])最终都为void foo(int *a).
这种情况(用指针替换数组类型)仅发生在实际数组中,而不是对数组的引用,因此void foo(int (&a)[5])可以工作(或int (*a)[5]在 C 中)。