The & address operator
- C++ course
- Beginner
- Lesson 78/116
- 5 min
Learn to take a variable's address with &.
The & address operator
The & address operator gives the memory address of a variable. The syntax: &x. This expression says where x lives in memory. It is often used when assigning to a pointer: int* p = &x;.
The address is a number depending on the variable's type; but printing it directly gives a system-specific format. Assigning the address to a pointer and accessing via *p is safer than dealing with the address directly.
Address and value
A variable has two sides: its value (content) and its address (memory location). x gives the value; &x gives the address. An int* pointer holds the address of an int.
To reach the value through a pointer, use * (dereference): *p gives the value at the address p holds. So after int x = 42; int* p = &x;, *p and x refer to the same value.
Practice Take an address and access the value
Declare int x = 42;. Assign x's address to p with int* p = &x;. Print the value p points to using *p with std::cout.
Starter code
#include <iostream>
int main() {
// Declare x
// Assign x's address to p
// Print the value
return 0;
}Sample solution
#include <iostream>
int main() {
int x = 42;
int* p = &x;
std::cout << *p << "\n";
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does this code print?
int x = 42;
int* p = &x;
std::cout << *p;- x's address
- 0
- 42 Correct answer
- Error
Explanation: *p gives the value of x, which is 42.
2 Address operator
int x = 42;
int* p = ____x;
int x = 42;
int* p = &x;
Explanation: int* p = &x; assigns x's address to p.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
int* p = &x |
Address assignment |
& |
Address operator |
p |
Holds the address |
*p |
Access value |