Local Variables
Inside a function, you can create variables, just like in main. But such a variable exists only inside the function: it's created when the function runs and disappears when the function ends. Outside the function, C++ doesn't know it:
#include <iostream>
#include <string>
void sayHello() {
std::string greeting = "Hello!";
std::cout << greeting << std::endl;
}
int main() {
sayHello();
std::cout << greeting << std::endl;
return 0;
}The program doesn't compile:
main.cpp:11:18: error: use of undeclared identifier 'greeting'
11 | std::cout << greeting << std::endl;
| ^~~~~~~~
1 error generated.On line 11, main tries to print the variable greeting, which exists only inside the function sayHello. Parameters are the same: they exist only inside their function.
The part of a program where a variable exists is called its scope. A variable created inside a function is local: it belongs only to that function. That applies to main too, because it's a function as well. So other functions can't see the variables of main:
#include <iostream>
#include <string>
void printLabel(std::string product) {
std::cout << shopName << ": " << product << std::endl;
}
int main() {
std::string shopName = "Pet Corner";
printLabel("dog food");
return 0;
}This program doesn't compile. The error use of undeclared identifier 'shopName' is on line 5, inside the function, which doesn't know the variable from main. When a function needs a value from main, pass it as an argument: give the function a parameter std::string shop and call it as printLabel(shopName, "dog food"). (Variables created outside all functions would be visible to all functions, but we don't use them in this course. In a longer program, it's hard to keep track of which function changed them.)
Every block in curly braces has its own scope. A variable created inside an if or a loop exists only up to its }, and the variable i from for (int i = 0; ...) exists only in the loop.
Why is it useful that local variables stay inside their functions?
- Functions don't get in each other's way. Two functions can each have a variable named
total, and those are two different variables: changing one doesn't change the other. - To use a function, you only need to know what to give it (the arguments) and what it gives back (the return value). How it works inside is its own business.
- Every call starts afresh: the variables of the function are created again, with nothing left over from the previous call.
A parameter is a local variable too. When the function is called, the parameter gets a copy of the argument. When the function changes the parameter, the variable in main stays the same:
#include <iostream>
void resetScore(int score) {
score = 0;
}
int main() {
int score = 10;
resetScore(score);
std::cout << score << std::endl;
return 0;
}This program prints:
10The function set its parameter score to 0. But the variable score in main is a different variable that only has the same name, and it stayed 10.
So the rule is simple: values go into a function through its parameters, and come out with return. When you need a value from inside a function, don't reach for its variable. Return the value and store it where you call the function.
Instructions
- 1
The program doesn't compile, because
totalexists only inside the function. Fix it: change the return type of the function tointand returntotalfrom it. Inmain, store the result of the calltotalPrice(25, 4)in a variablebill, and printbillinstead oftotal. The program prints100. - 2
Every order also costs delivery. Its price is in the variable
deliveryinmain. The function can't see it, because it's local tomain. Give the function a third parameter,deliveryof typeint, add it to the total inside the function, and pass it the variabledeliveryin the call:totalPrice(25, 4, delivery). The program then prints105.