Sunday, 8 September 2013

When to pass a C++ variable as a reference?

When to pass a C++ variable as a reference?

I was wondering whether the C++ purists here could clarify for me when the
appropriate scenario is to pass a reference of a variable into a function.
From reading C++ Primer, I thought I had learned that you do this when you
intend to modify the actual variable passed in, rather than creating a
copy that is modified in the scope of the function (before being destroyed
when the function is done being used). However, I've seen several code
examples where a variable is passed in as a reference even though it is
not being modified.
Here's one, Wikipedia's example of Kadane's algorithm:
int sequence(std::vector<int>& numbers)
{
// Initialize variables here
int max_so_far = numbers[0], max_ending_here = numbers[0];
// OPTIONAL: These variables can be added in to track the position of
the subarray
// size_t begin = 0;
// size_t begin_temp = 0;
// size_t end = 0;
// Find sequence by looping through
for(size_t i = 1; i < numbers.size(); i++)
{
// calculate max_ending_here
if(max_ending_here < 0)
{
max_ending_here = numbers[i];
// begin_temp = i;
}
else
{
max_ending_here += numbers[i];
}
// calculate max_so_far
if(max_ending_here >= max_so_far )
{
max_so_far = max_ending_here;
// begin = begin_temp;
// end = i;
}
}
return max_so_far ;
}

No comments:

Post a Comment