Function Parameters

printLine from the last lesson prints the same thing every time. Most functions are more useful when you can give them values to work with. You give values to a function through its parameters.

#include <iostream>
#include <string>
using namespace std;

void priceTag(string item, double price) {
    cout << item << ": $" << price << "\n";
}

int main() {
    priceTag("Coffee", 3.5);
    priceTag("Sandwich", 7.25);
    return 0;
}

Output:

Coffee: $3.5
Sandwich: $7.25

Inside the parentheses, priceTag lists two parameters: item, a string, and price, a double. A parameter is a variable that belongs to the function. Each time you call the function, the parameters get the values you write in the call. Those values are called arguments.

The arguments are matched to the parameters by position. In the first call, "Coffee" goes into item and 3.5 goes into price. In the second call, the same body runs with different values, so it prints a different line.

Each argument must fit the type of its parameter, and you must give every one of them. A call with a missing argument does not compile:

#include <iostream>
#include <string>
using namespace std;

void priceTag(string item, double price) {
    cout << item << ": $" << price << "\n";
}

int main() {
    priceTag("Tea");
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:10:13: error: too few arguments to function ‘void priceTag(std::string, double)’

The call on line 10 gives only the item, so the compiler stops with "too few arguments". The message also shows what the function expects: a string and a double. (std::string is the full name of string.)

The function gets a copy

A parameter holds a copy of the argument. If the function changes its parameter, the caller's variable does not change:

#include <iostream>
using namespace std;

void addBonus(int score) {
    score = score + 10;
    cout << "Inside: " << score << "\n";
}

int main() {
    int points = 50;
    addBonus(points);
    cout << "Outside: " << points << "\n";
    return 0;
}

Output:

Inside: 60
Outside: 50

addBonus added 10 to its own copy, so it printed 60. The variable points in main is still 50. This is called pass by value, and it is how C++ passes arguments unless you ask for something else. The References lesson, later in this section, shows how a function can change the caller's variable.

Default values

A parameter can have a default value. If the call leaves that argument out, the default is used:

#include <iostream>
#include <string>
using namespace std;

void greet(string name = "friend") {
    cout << "Hello, " << name << "\n";
}

int main() {
    greet("Alice");
    greet();
    return 0;
}

Output:

Hello, Alice
Hello, friend

In the exercise, the body of a function and its calls are already written. Fill in the types in its parameter list.