Pointers and References C++
Pointers and references as parameters
Pointer
We pass the address of integer x and the address of integer y to the function.
void swap1(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x = 6;
int y = 9;
swap1(&x, &y); // x = 9, y = 6
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Reference
int &a = x represents a is a reference to x (a nickname to x), int &b = y represents b is a reference to y (a nickname to y). So a and b mean x and y themselves. Changing a and b will result in the change of x and y.
void swap2(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int x = 6;
int y = 9;
swap2(x, y); // x = 9, y = 6;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Non-pointer and non-reference
x and y will not be swapped successfully because we only pass a copy of them into the function here.
void swap3(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int x = 6;
int y = 9;
swap3(x, y); // x = 6, y = 9
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
