As I got stuck between whether shortening the question or clarifying it, I do not think I can be understood with the question sentence. I tried to explain myself with examples here:
Let's see a non-working void function for decreasing a variable by 1 :
#include <iostream>
using namespace std;
void decrease (int a)
{
a--;
}
int main ()
{
int x = 17;
decrease (x);
cout << x << endl;
}
As expected it prints 17
. The reason is super clear because when a variable is passed to a function, actually what it is passed is a copy of the original variable (they hold same values, but they are in different addresses) and therefore all the modifications are done to the copy of that variable, and the copy is destroyed after function terminates.
What we need here is pointers. If we modify the above code piece like this :
#include <iostream>
using namespace std;
void decrease (int* a)
{
(*a)--;
}
int main ()
{
int x = 17;
decrease (&x);
cout << x << endl;
}
It works because what we passed in the line decrease (&x)
is a copy of the x
's address. The decrement is done to the value of our copy, and because the value of it is equivalent to x
's address the decrement effects address' value, which is the value the original x
holds.
So far all is understandable. But when we solve the issue by references like below :
#include <iostream>
using namespace std;
void decrease (int&a)
{
a--;
}
int main ()
{
int x = 17;
int& y = x;
decrease (y);
cout << x << endl;
}
How is this situation explained? When we decrease the copy of the reference of x
, isn't it the same with trying to decrease the copy of x
?
If so, what makes references work here? Why does it work when the first code piece doesn't work?
How does it modify the actual value of x
?
NOTE : I found a post of user @Angew is no longer proud of SO stating that whether a reference takes memory or not is unspecified. As he stated, if we consider that references take memory in this kind of implementation and references behave like pointers I think it gets explainable, but still confused with the usage.
EDIT : I was using C and I decided to move on with C++, that is why I can't get the logic of references.