The & and * Signs
You now know two meanings for each of the signs & and *, and beginners often mix them up. What matters is where they stand:
- In a declaration, when you create a variable or a parameter, they stand right after the type and are part of the type. Read
int&as "reference to an int" andint*as "pointer to an int". - In an expression, code that calculates, assigns or prints something, they stand before the name of a variable and do something with it.
& | * | |
|---|---|---|
| In a declaration (after a type) | int& r = x; reference: r is another name for x | int* p = &x; pointer: p holds the address of an int variable |
| In an expression (before a variable) | &x is the address of the variable x | *p is the variable that p points to |
And when * stands between two values, as in price * 2, it's plain multiplication. The double && you know from conditions, where it means "and". This example has almost all the meanings:
#include <iostream>
int main() {
int x = 5;
int& r = x; // declaration: r is a reference to x
int* p = &x; // declaration: p is a pointer; expression &x: address of x
*p = r * 2; // expression: *p is the variable x, r is x too, * between them multiplies
std::cout << x << std::endl;
return 0;
}This prints:
10When you mix them up, the compiler usually tells you, and it often finds several errors at once. Fix them starting with the first one, as usual.
Instructions
The program doesn't compile: the compiler finds errors on lines 5, 6 and 9. Use the table to fix the & and * signs so that each line does what its comment says. The program then prints Score: 120.
But the last line prints an address instead of the score, such as Through the pointer: 0xfff4. Fix it so that it prints the value through the pointer: Through the pointer: 120.
Start programming for free
6/10