Arrays can be passed as pointer to a function or even as reference. Passing it as reference gives an alias on which sizeof and count operators will also work. This makes pass by reference look superior.
However, pass by pointer seems to be the norm in books. Why? Is there something I particularly need to know about pass by reference for arrays?
Passing by reference means that your function can only accept fixed-size arrays (that's why it knows their size, because the compiler enforces it). Passing by pointer means otherwise. Also, passing by pointer lets you pass nullptr
, for better or worse.
I usually use std::vector
and like to pass by const reference. That said, if my api may at some point be called by c code, using pass by const pointer may make sense, though you then have to also want to send down the size. If the function may be called with an std::array
or a std::vector
, you could decide to send down a pointer (and size), or a set of iterators (begin/end).
If we are talking about using std::array, the template argument requires the size of the array. This would mean in a normal function, you'd need a fixed size:
void myfunc( const std::array<int, 5>& mydata ){...}
However, if we do a templated function, templating on size, that is no longer a problem.
template<unsigned int SZ>
void myfunc(const std::array<int, SZ>& mydata) {...}
If we are talking about stack allocated c-style arrays... Good C++ style is to prefer std::array/std::vector to c-style arrays. I would recommend reading C++ Coding Standard by Herb Sutter chapter 77 on page 152 speaks about the subject. When using c-style arrays, sending down the pointer and size is the standard way to go.
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