By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,247 Members | 1,057 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,247 IT Pros & Developers. It's quick & easy.

concerns about passing arrays into functions

P: 1
how to pass arrays into the function and what is the use of functions.what do you mean by a modification of the array values in the function and does the modification of the values occur only inside the function or does it happen globally
Jun 7 '07 #1
Share this Question
Share on Google+
2 Replies

P: 1,806
If you pass a reference to the array to the function, all modification is global, however you can copy it to a local array if you want to avoid this.

Alternatively, I'm pretty sure you can pass the actual array (or at least a copy of) to a method, in which case all modification is local ot the method (I think)....
Jun 7 '07 #2

Expert Mod 5K+
P: 9,197
You do not pass arrays to functions. What you pass is the name of the array. In C and C++ the name of the array is the address of element 0. So, what is actually passed is the address of the array.

That means any change to the array from inside the function changes the array used on the call.

What is the purpose of a function? Suppose you have an array of 5000 persons and you need to display the person's name and address. You have two choices: a) write the display logic 5000 times, once for each person, or b) write the display logic once, put it in a function, and call the function 5000 times from inside a loop. Your choice.

As to whether modifications made inside a function are local to the function or are made globally is based on the function arguments. All arguments are copies of the variables used on the call. Hence, all modifications are local.
There are two exceptions.

The first exception is a pointer argument. The pointer the function uses is still a copy of the original ione used on the call, but the pointer has the address of some data that is outside the function. By using the pointer inside the function, you change data outside the function.

The second exception is a reference argument (C++ only). A reference is not a copy. Instead, it is an alias for the original object. Any changes to the reference also change the original object since the reference is the original object.

You must look at each argument and ask yourself: Is this a copy? If yes, all chnages are local. If not, all changes are global.
Jun 8 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.