Why can’t you pass arrays as function arguments?
I have been reading this C++ book that says ‘you can’t pass arrays as function arguments’, but it never explains why. Also, when I looked it up online I found comments like ‘why would you do that anyway?’ It’s not that I would do it, I just want to know why you can’t.
They can:
In technical terms, the type of the argument to
foois “reference to array of 5constints”; with references, we can pass the actual object around (disclaimer: terminology varies by abstraction level).What you can’t do is pass by value, because for historical reasons we shall not copy arrays. Instead, attempting to pass an array by value into a function (or, to pass a copy of an array) leads its name to decay into a pointer. (some resources get this wrong!)
Array names decay to pointers for pass-by-value
This means:
There’s also the hugely misleading “syntactic sugar” that looks like you can pass an array of arbitrary length by value:
But, actually, you’re still just passing a pointer (to the first element of
ar).foois the same as it was above!Whilst we’re at it, the following function also doesn’t really have the signature that it seems to. Look what happens when we try to call this function without defining it:
So
footakesint*in fact, notint[5]!(Live demo.)
But you can work-around it!
You can hack around this by wrapping the array in a
structorclass, because the default copy operator will copy the array:This is somewhat confusing behaviour.
Or, better, a generic pass-by-reference approach
In C++, with some template magic, we can make a function both re-usable and able to receive an array:
But we still can’t pass one by value. Something to remember.
The future…
And since C++11 is just over the horizon, and C++0x support is coming along nicely in the mainstream toolchains, you can use the lovely
std::arrayinherited from Boost! I’ll leave researching that as an exercise to the reader.