-7

in below code why its displaying 2,3 though we change the address. why not 3,2.

#include <iostream>
using namespace std;

void Addresschange(int *a, int *b)
{
 int *t;
 t = a;
 a = b;
 b = t;
cout << *a<<endl<< *b<<endl;//here its displaying 3,2
}

int main ()
{
  int a = 2 ,b = 3;
  Addresschange(&a ,&b);
  cout << a<<endl<< b;//why its displaying 2,3 here
  return 0;
}

So after going out of this function the addresses of the actual parameters (a and b) would be changed. Is it possible at all?

Jeggu
  • 569
  • 2
  • 10
  • 26

1 Answers1

3

In the Addresschange function, a and b are local variables. When you change their values, that only changes their values inside the function. So your code just swaps the values of a and b inside the Addresschange function. It doesn't use any pointer operations, so even though the values happen to be pointers. that doesn't change the fact that they're passed by value and that means that changing the value won't propagate out of the function.

If you want to change something's value using a pointer, you have to pass a pointer to it and change the value the pointer points to. So if you want to change the value of an int *, you need to pass the function an int **.

Your function passes an int * (pointer to int), which lets you change the value of an int. For example, *a = 3; will make a equal to 3 instead of 2 in the caller, using the pointer that was passed by value to change the value of the thing it points to.

(You can also use references in C++. You still can't "reseat" a reference to make it refer to something else unless you use something like std::reference_wrapper.)

David Schwartz
  • 179,497
  • 17
  • 214
  • 278