Pointer Programs
Start with Pointer Programs
Learn pointer programs through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of pointer programs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Pointers are values that hold addresses. Passing a pointer lets a function update the storage it points to, while passing a plain integer makes a copy of its value.
The example uses pointers to update a score without relying on the actual memory address, which varies between runs.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func addBonus(score *int, bonus int) { *score += bonus }
func main() {
score := 70
addBonus(&score, 10)
fmt.Println("Score:", score)
}
Output
Score: 80Trace what the program does
&score produces a pointer to the score variable. The function dereferences the pointer, adds ten, and the caller observes the new value 80.
Avoid common mistakes
- A nil pointer must not be dereferenced.
- A pointer argument is itself passed by value; it is not proof that Go uses pass-by-reference parameters.
Try it yourself
Add a function that swaps two integer variables using two pointers.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Pointer Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.