C++ · Beginner level

Beginner level · Module 2: Control Flow and Functions in C++ · Lesson 2 of 3

Writing Functions

Break programs into functions, declare them before use and return results.

In this lesson you will

  • Write functions with parameters and return values
  • Use function declarations and overloading

Key concepts

function definitiondeclaration (prototype)return typeoverloading

The lesson

A function groups code under a name: double area(double width, double height) { return width * height; }. Its signature is the return type, name and parameter types. void functions return nothing.

The compiler reads files from top to bottom, so a function must be declared before it is called. Put a declaration (prototype) such as double area(double, double); near the top, or in a header file, and the definition later.

Overloading lets functions share a name if their parameters differ, for example print(int) and print(const std::string&). Keep functions short and focused; a function that needs a long comment to explain what it does probably does too much.

Step by step

  1. Write a function to classify a mark.
  2. Move main to the top and add a declaration for the function.
  3. Write two overloads of a formatting function.
  4. Refactor a long main into three functions.

Practice activity

Refactor the till program so input, calculation and printing are separate functions.

Expected result: main is a few lines of calls, and the output matches the original program.

Check your understanding

  1. Why might you need a function declaration?

    Show answer

    So the function can be called before its definition appears in the file.

  2. Can two functions share a name in C++?

    Show answer

    Yes, if their parameter lists differ — this is overloading.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.