CodeBlanks Logo Icon CodeBlanks

Defining functions

Learn how to define and call a function.

What is a function?

A function is a named, reusable block of code. You define it once and call it as many times as you like. The definition void greet() { std::cout << "hi"; } creates a function named greet.

Every function has a signature: return type, name and parameter list. The signature of void greet() reads 'greet, no parameters, returns nothing'. To call it you write its name followed by parentheses: greet();. This runs the code inside the function.

Definition vs call

The definition and the call of a function are different things. The definition says what the function does: void greet() { std::cout << "hi"; }. The call runs it: greet();.

In C++ the call can sit below or above the definition; as long as the compiler sees the definition, order does not matter. For readability it is common to place definitions before main. You can call a function many times; each call runs the same code again.

Practice Define greet and call it

Define a void greet() function whose body is std::cout << "hi" << std::endl;. Call it from main.

Starter code

main.cpp
#include <iostream>

// Define greet here

int main() {
    // Call greet
    return 0;
}

Sample solution

main.cpp
#include <iostream>

void greet() {
    std::cout << "hi" << std::endl;
}

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

Expected output

hi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What do you write to call a function?

main.cpp
void greet() { std::cout << "hi"; }
  • greet;
  • greet(); Correct answer
  • call greet();
  • greet->();

Explanation: greet(); runs the function.

2 Complete the function call

Question
greet____;
Answer
greet();

Explanation: greet() calls the function.

3 Match the function parts

Term Meaning
void Return type
greet Function name
() Parameter list
greet(); Call

All lessons in Beginner