2

Is it possible to pass an array by value to a C++ function?

If it is, how would I do that?

1
  • In C, no, in C++, yes, via std::vector. Commented Mar 12, 2013 at 11:20

4 Answers 4

6

If by array you mean raw array, then the answer is No. You cannot pass them by value either in C or C++.

Both the languages provide a workaround, where you can wrap a struct around that array and pass its object. Example:

struct MyArray { int a[100]; };
...
struct MyArray obj; // `obj.a[]` is the array of your interest
foo(obj);  // you have passed the `a[]` by value

In C++, such structs are readily available in form of std::vector and std::array.

Sign up to request clarification or add additional context in comments.

Comments

4

Definitely:

void foo(std::array<int, 42> x);

2 Comments

+1, that is exactly what I was going to answer, down to the 42.
By the way, std::array is not an array.
0

Normally passing an array to a function makes it decay to a pointer. You implicitly pass the (start-)address of the array to the function. So you actually can't pass an array by value. Why don't you use va_args if you want to pass the contents by value?

Comments

0

Yes, you can. You can implement it by using a pointer as the argument, but in the function body, you can use the copy mothord (the exact name I can't remember) to copy it.

4 Comments

The whole point of "passing the array by value" is that that you are, well, passing the array by value. If you pass a pointer and then copy, you may be able to model this behaviour, but you are still only passing the pointer by value, not the array.
Yeah, you are right. And what the asker wants is just "pass an array by value". I think what he means is to pass the entire array, just as what you comment on me: passing the array by value. Can I say that?
The problem with your approach is unclear distribution of responsibilities: Does the caller copy the array or does the callee? You may get this right when all of the code is your own, but it would get increasingly complex with libraries etc. That's why it's a better idea to use proper pass-by-value with std::vector or std::array in C++.
Ok, I see it. You are right. That's really a much better way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.