Ian Burris
Ian Burris

Reputation: 6515

How to get the value of a value passed by reference in C++

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?

Upvotes: 1

Views: 259

Answers (3)

Oren S
Oren S

Reputation: 1872

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.

Upvotes: 3

unwind
unwind

Reputation: 399979

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. */

Upvotes: 12

Naveen
Naveen

Reputation: 73473

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

Upvotes: 2

Related Questions