Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

why won't the value change?

adam2016adam2016 DubMember Posts: 1
edited July 2016 in Beginner C/C++

I know how passing by ref and value works well I thought I did haha

but I'm still confused as to why this line of code does not change the value in number

include

using namespace std;

int functionA(int *x){

int y = 55;
x = &y;
return *x;
}

int main()
{

int number = 60;
cout << &number << number << endl;
functionA(&number);
cout << number;

}

and why this code does actually DOES change the value of x

include

using namespace std;

int functionA(int *x){

 *x = 70;
 return *x;

}

int main()
{
int x = 60;
cout << x << endl;
functionA(&x);
cout << x << endl;

so for the first example,I'm passing by reference(memory location) of the integer variable number and it gets passed into the function functionA,now line 14 I thought I'm changing where x(address of number) is pointing to by assigning x to the address of y(&y) now by doing this I thought I would change the value of number to y which is 55 but yet this does not happen,I don't understand why the value does not change here.now somebody on another forum mentioned that I am not actually passing by reference but actually passing a copy of a pointer(passing by value) that makes the most sense so far but I always thought that when you pass a pointer or memory address into a function the value in the original pointer or memory address that you passed gets modified ??

thanks,

Adam

Tagged:
Sign In or Register to comment.