Boyan Kushlev
Boyan Kushlev

Reputation: 1053

Using alias in C++ without altering value of original variable?

So I have to make a program where I calculate the sum of some elements in an array and then find the number of digits of the sum (e.g. if the sum of several elements is 175, I have to print the value of the sum (175) and the number of digits of 175 (3)).

To determine the number of digits I use the following "while" loop:

while (sum > 0)
{
    sum /= 10;
    digits++;
}

As you might have noticed, at the end of the loop the sum is 0. So I thought of creating an alias of "sum":

int& rSum = sum;

So I simply substituted "sum" with "rSum" in the array, in order to find the numbers of digits, and printed sum in the end of the program. Anyways, the value of "sum" after the loop is 0, in other words equal to "rSum". So I guess, when you create an alias to a certain variable, modifying the alias, modifies the variable itself, which is a problem in my case.

My question is, can I create the program with aliases (or using references, pointers etc.), or is the only way by creating a copy of the "sum" variable (int rSum = sum;)?

Upvotes: 0

Views: 280

Answers (3)

rockoder
rockoder

Reputation: 747

This will also create copy of sum but at least it wont be you:

const int& orgSum = sum + 0;

while (sum > 0)
{
    sum /= 10;
    digits++;
}

cout << orgSum << endl;

Upvotes: 0

Kos
Kos

Reputation: 72241

Your question looks like "how can I make a copy this variable without making a copy of this variable?".

I think your concern roots one level lower, you think making a copy would make the code less readable - and I agree. But you can combat it very simply:

int sum = ...;
int digits = countDigits(sum);

Extracting countDigits to a separate function will still make a copy of your sum variable, since it's copied by value (which is OK), but this copy will be temporary (local to countDigits) and won't make an unneccessary mess in your original function.

Upvotes: 3

robert
robert

Reputation: 3726

Skizz proposes here a logarithm based method: Efficient way to determine number of digits in an integer. Or look at Brad's solution. However, if you use division you will need a copy.

Upvotes: 0

Related Questions