Small Steps I — Creating with Text and Numbers
Using separate variables inside a function
Predict the two outputs when score starts at 20, then check your prediction.
What you will learn
A local variable created inside a function is used within its scope. A parameter passed by value also holds a value separately from the original.
Try it
Example · example.cpp
void add_one(int number)
{
number = number + 1;
print(number);
}
void small_main()
{
int score = 10;
add_one(score);
print(score);
}
number receives a copy of score's value, 10. Only number changes, so score is still 10 when the function returns.
Ordinary local variables reach the end of their lifetime when their scope ends. They do not automatically remember a value for the next call. Later lessons on references show how to change the original.
Expected output:
11
10
Exercise
Predict the two outputs when score starts at 20, then check your prediction.
Exercise starter · exercise_starter.cpp
void add_one(int number)
{
number = number + 1;
print(number);
}
void small_main()
{
int score = 10;
add_one(score);
print(score);
}
Hint
Change the parts of the example that you need.
show solution
void add_one(int number)
{
number = number + 1;
print(number);
}
void small_main()
{
int score = 20;
add_one(score);
print(score);
}