6.3 — Inputs: parameters

📘 Chapter 6⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Sending values in#

Parameters let you send values into a function. They go inside the ( ).

C++▶ Run
void greet(std::string name){    std::cout << "Hi, " << name << "!\n";} int main(){    greet("Ana");    greet("Ben");    return 0;}
Output
Hi, Ana!Hi, Ben!
Parameter vs argument

The parameter is the box in the function (name). The argument is the value you send in when calling ("Ana").

Many parameters#

Separate them with commas:

C++▶ Run
int add(int a, int b){    return a + b;} int main(){    std::cout << add(3, 4) << '\n';          // 7    std::cout << add(add(1, 2), 10) << '\n'; // 13    return 0;}

Copies go in#

By default, the function gets a copy of the value. Changing the copy does not change the original.

C++▶ Run
void tryToChange(int x){    x = 100;   // only changes the copy} int main(){    int n { 5 };    tryToChange(n);    std::cout << n;   // still 5    return 0;}

This is called pass by value. To change the original, you need a reference — see 9.3 — Passing by reference.

Default values#

Parameters can have a default value, used when you leave them out:

C++
void printStars(int count = 10){    for (int i { 0 }; i < count; ++i)        std::cout << '*';    std::cout << '\n';} printStars(3);   // ***printStars();    // **********
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.