Variables and Memory
int x = 10; // box named x stores 10
Pointers ( and &
)
int x = 10;
int* p = &x; // p stores the address of x
*p = 20; // changes the value at that address → x becomes 20
&x
= “address of x”p
= “value at the address p points to”References (&
)
int y = 5;
int& ref = y; // ref is another name for y
ref = 15; // changes y to 15
⚖️ Key difference:
p
); reference acts like the variable itself.Basics
Declare an integer a = 42
.
Create a pointer p
to a
.
Print a
, &a
, p
, and p
.
What’s the difference?
Modifying Values
p
to change the value of a
to 99.r
to a
and change a
to 123 using r
.a
after each change.Pointers and Functions
void square(int* n)
that squares a number using a pointer.References and Functions
void square(int& n)
.Challenge
Write a function swap
in two versions:
a) Using pointers
b) Using references
Test it with two integers and see both work.