6.1 — What is a function?
Read one box at a time. No rush.
A saved action#
A function is a group of steps with a name. You write it once, then use it as many times as you like.
You already know one function: main. Now let's make our own.
C++▶ Run
#include <iostream> void sayHello(){ std::cout << "Hello there!\n";} int main(){ sayHello(); sayHello(); return 0;}Output
Hello there!Hello there!The parts#
void= this function gives nothing back (more on that soon).sayHello= the function's name.()= where inputs go. Empty means no inputs.{ }= the steps.
Calling a function#
Writing sayHello(); is called calling the function. The program jumps into the function, runs its steps, then comes back to where it was.
Key idea
Functions let you name a job and reuse it. If the same code appears twice, it probably wants to be a function.
Watch out
You cannot put a function inside another function. Write them one after another, at the top level of the file.
Tip: press ← / → to move between lessons, / to search.