pointers

Hello,

i am reading article about pointers. and there is a code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <iostream>
#include <conio.h>

void not_alter(int n) 
{
	n = 360;
	std::cout << n << "\n";
}

void alter(int *n)
{
	*n = 120;
	std::cout << *n << "\n";
}

int main(void)
{
	int x = 24;

	alter(&x);
	not_alter(x);
	std::cout << x;

	_getch();
	

	return 0;
}


the output is:

1
2
3
120
360
120


why value of x is not changed after not_alter() function is called? thank you for your answer.
Last edited on
Because it's passed as a straight arg rather than as reference or pointer. Think of it this way:
In not_alter, it's passing the value of n. It's not actually passing n. It's like taking a photo of a guy and drawing stuff on it; the guy's face doesn't change. It's just a photograph. When an arg is passed without pointer or reference it is a copy of that argument that is created within function scope, and then that is modified. The original remains untouched.
WHen you pass a pointer (or the more common reference) however, you are passing the address of the object or variable and not its value. By dereferencing that pointer you are now referring to the original object and thus changes therein are made on the original and not a copy.
you explained that to me very well. i get it now. thank you. :)
Topic archived. No new replies allowed.