I have a broad level question regarding best practices for passing arrays into functions.
So in the past when I've been programming in C and I wanted a function to have it's input be an array, I would declare that functions input parameters to be a pointer. This worked relatively well.
However, I've began programming more in C++ and am trying to determine the best practice for passing arrays into functions. So I've noticed that it is popular in C++ to pass objects by reference such that expensive copying operations are avoided. However, when I google passing arrays into functions, I read statements saying that arrays are automatically passed by reference.... So what's the deal with this? Why are arrays automatically passed by reference? And let's say I don't want the function to modify the array, is it possible to pass const arrays?
I'm having a difficult time getting my test program to compile. So I'm curious if anyone could explain what it means to pass an array into a function in C++ and how that differs from C.
Thanks!
In both C and C++, declaring a function to take an array parameter, such as in the following example, in fact causes the function to take a pointer. For example:
void foo(int arr[]);
This function signature is identical to:
void foo(int *arr);
Thus when you try to pass an array in either C or C++ you're already avoiding any overhead of copying an array.
Why are arrays automatically passed by reference?
They're passed by reference only in a loose sense. They're not literally passed as a C++ reference, which would look like the following:
void foo(int (&arr)[10]); // arr is a reference to an array of 10 ints
The reason for the C behavior is because they thought passing arrays by value would never be used anyway because of the expensive copy. The reason C++ has the same behavior is simply for compatibility.
Experience has shown that the special behavior of array parameters was a bad idea, and so it is one of the many reason that one should avoid using raw arrays in C++. The problem is that passing an array either way is dangerous:
void foo(int arr[10]) { arr[9] = 0; }
void bar() {
int data[] = {1, 2};
foo(data);
}
The above code is wrong but the compiler thinks everything is fine and issues no warning about the buffer overrun.
Instead use std::array or std::vector, which have consistent value semantics and lack any 'special' behavior that produces errors like the above.
And let's say I don't want the function to modify the array, is it possible to pass const arrays?
You can:
void foo(int const arr[]);
void foo(int const *arr);
void foo(int const (&arr)[10]);
So I'm curious if anyone could explain what it means to pass an array into a function in C++ and how that differs from C.
If you use the syntax that works in C then it doesn't really differ at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With