Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it normal to pass array reference to function

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?

like image 416
quantum231 Avatar asked Feb 24 '16 13:02

quantum231


2 Answers

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.

like image 184
Yam Marcovic Avatar answered Oct 28 '22 08:10

Yam Marcovic


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.

like image 39
Atifm Avatar answered Oct 28 '22 10:10

Atifm