views:

132

answers:

3

I have a function with the following declaration:

void cleanValid(int valid[][4], int &size, int index);

In implementation of this function I need to set another counter equal to the integer size passed by reference. I tried doing something like:

int count;
count = size;

If I'm not mistaken, when I change the value of count it will change the value of size as well. I can't have this happen though. How would I go about copying the value of size into count and keeping them independent?

+12  A: 

No, you've got it wrong. When you read from the reference into a non-reference variable, you're not setting up any kind of linkage between the two. You will have an independent copy of the value of size at that time, nothing else.

If you wanted to affect the value of size, you would have to use a reference to it:

int& count = size;

/* ... */    
count= 32;  /* This will change size, too. */
unwind
+2  A: 

int count = size copies the value of size into count. If you change count since you are modifying a copy, size will remain unaffected.

Naveen
+3  A: 

If you don't want size to change, why not pass by value/const reference?

void cleanValid(int valid[][4], int size, int index);

or

void cleanValid(int valid[][4], const int &size, int index);

in both options you ensure size is not changed - by letting the compiler take care of it.

Oren S
Plus, in the first example you have the advantage of being able to use size directly. You can do whatever you want with it, and you don't need to copy it again into a local variable. Also, in some cases an int is smaller than a reference, so there can be less to copy.
Adhemar