Sign in to follow this  

Can I pass an array "by value" as a function argument in C++

This topic is 3573 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, Is it possible to pass the array by value as below: 1) void f(int a[3]) like you do, when you pass a variable by value in 2) 2) void f(int a) In case 1) the compiler doesn't give any errors, but I can't figure out how to initialize this temp array during the function call: 3) f((1,1,1)) ? like I would do for 2) in 4) 4) f(2) Questions: 1. Is a temporary array being created in call 1) 2. How to initialize this array during the function call like in 3),4) Thanks!

Share this post


Link to post
Share on other sites
No, arrays are always passed by reference (Since the compiler passes the address of the first element). If you use a std::vector, you can pass by value though.

It'd be better to pass by const reference anyway, to avoid any unnessecary copying.

As for how to call the function, have you tried:
f({1, 1, 1});
?
I haven't tried it myself, so it may well not work at all. You could always do:
{int a[] = {1, 1, 1};
f(a);}

Share this post


Link to post
Share on other sites
You cannot pass arrays by value in C++.

A function taking an array as an argument is identical to one taking a pointer to the array's type.

Relevant reading:
link
link

You could wrap the array in a structure, then pass the structure by value (boost::array comes to mind). That is about the closest you'll get. Or use some kind of container class.

Share this post


Link to post
Share on other sites

This topic is 3573 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this