Reputation: 598
I understand how arrays can be passed to functions in c++, but I don't understand what is the point of including array's size in a function declaration when this size is ignored anyway, because what we are really passing to function is a pointer to the first element of the array.
For example if we have following code:
void ArrayTest1(int(&ints)[3])
{
for (int i = 0; i < 3; i++) std::cout << ints[i];
}
void ArrayTest2(int ints[3])
{
for (int i = 0; i < 3; i++) std::cout << ints[i];
}
void ArrayTest3(int ints[])
{
for (int i = 0; i < 3; i++) std::cout << ints[i];
}
int main()
{
int ints[] = { 1, 2 };
//ArrayTest1(ints); //won't compile
ArrayTest2(ints); //ok
ArrayTest3(ints); //ok
return 0;
}
Then from what I understand functions ArrayTest2
and ArrayTest3
are identical.
Is syntax used in ArrayTest2
only meant to make it clear that this function expects an array with 3 elements and passing array with a different size can cause errors? I'm not new to programming, but I'm new to c++ so I'd like to know what is the point of such syntax and when do people use it.
Upvotes: 2
Views: 702
Reputation: 17454
I don't exactly know why C permits this (yes, this comes from C), but it is indeed pointless.
Worse than that, the "wrong" dimension would be very misleading to readers of your code.
We might argue that it was to keep the language grammar simple, as the grammar of a declarator already makes the dimension optional (consider int x[] = {1,2,3}
vs int x[3] = {1,2,3}
).
Maybe some people use it to document intent; I certainly never would.
Upvotes: -1
Reputation: 2647
One of C++’s major design goals was far reaching compatibility with C. Not supporting all aspects of C-array usage would have been seriously detrimental to this goal.
Your examples even give a good indication that compatibility is indeed the intent, and that C++ would work differently if that hadn’t been the case. Consider your ArrayTest1()
. It takes a C-array by reference, something that does not exist in C. And in this case the array dimension is significant.
// C-array of length 3 taken by reference
void foo(int (&x)[3]);
void bar() {
int a[4] = {1,2,3,4};
foo(a); // Does not compile. Wrong array size.
}
Only ArrayTest2()
and ArrayTest3()
are exactly equivalent to:
void foo(int*);
Btw: Bjarne Stroustrup’s The Design and Evolution of C++ is a good read if you’re interested in why C++ is designed the way it is.
Upvotes: 1