A girl and a robot thinking together

Think together · First, a short story

The girl gives the robot a card that says “ring the bell twice.” Writing the instruction on the card and asking the robot to carry it out are two different moments.

Lay out the process

Follow the numbered steps, then explain them in your own words.
  1. DefineSpecify two rings
  2. CallRequest that it run
  3. Function bodyRing once, then again
  4. ReturnContinue the next task

A definition specifies a function’s name, inputs, and actions; a call asks the program to perform those actions.

You can call the same function many times. Each call performs the function’s task once.

01How do you define a simple function?

void sayHello() {
    std::cout << "Hello!\n";
}

Here:

void

Return type: no value is returned.

sayHello

The function name.

()

The parameter list, empty here.

{ ... }

The function body.

02How do you call a function?

int main() {
    sayHello();
    sayHello();
    return 0;
}

Write the function name followed by parentheses to make a call. This example calls it twice, so it prints two greetings.

03What is the difference between defining and calling?

Define a function

Specify what the function does.

Call a function

Ask the program to run it now.

A function is usually defined once and can be called many times.

04Why might a function need to appear before main?

When the compiler reaches a call, it needs to have already seen a declaration for that function.

void sayHello();  // Function declaration

int main() {
    sayHello();
}

void sayHello() { // Function definition
    std::cout << "Hello!\n";
}

A function declaration is also commonly called a function prototype.

05Are a declaration and a definition the same?

No.

Declaration

int add(int a, int b);

Tells the compiler the function’s name and type.

Definition

int add(int a, int b) {
    return a + b;
}

Provides the actual function body.

06Can a function have any name?

A function name must follow C++ identifier rules, and should ideally describe its purpose.

Clear

calculateSum

Clear

printScore

Unclear

abc

What have you learned?

  • A function definition includes a return type, name, parameter list, and body.
  • A function call uses the name and parentheses.
  • Defining and calling are two different actions.
  • The compiler must see a function declaration before its call.
  • A declaration and a definition are not the same thing.

Next: How are arguments passed to a function?

Your turn to try

A function prints two stars each time. How many stars are printed when it is called three times?

Ready? Open the explanation

Six stars: two per call, for three calls, so 2 × 3.