With pointers, const can protect two different things: the value reached through the pointer, or the pointer's own stored address. Read the spelling carefully rather than treating every appearance of const as the same promise.
| Declaration | What may change through this name? |
|---|---|
const int* view = &count; | The pointer may select another target; the target may not be edited through view. |
int* const link = &count; | The integer may be edited through link; the pointer must keep its initial target. |
const int* const fixedView = &count; | Neither the selection nor the integer may be changed through this name. |
The const before int applies to the pointed-to integer. The const after * applies to the pointer itself. A read-only access path does not make an originally writable integer globally immutable; another writable name can still change it.
#include <iostream>
int main() {
int left = 2;
int right = 6;
const int* view = &left;
view = &right;
int* const link = &left;
*link += 3;
std::cout << *view << '\n';
std::cout << left << '\n';
}
The example prints 6 and 5. The first assignment changes a selection, not an integer. The second assignment changes an integer, not a selection. Both operations respect their declarations.
Keep both pointer declarations unchanged in the starter. At the first TODO, assign to view itself to select another address. At the second, update the integer reached through link, not link itself. If the compiler rejects an assignment, check which side of * the declaration puts const on before changing any types. The declarations already allow the operations requested here.
second to view. Expect Viewed: 10.link. Expect Linked: 9.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.