Creating Your Own Functions

What is a function?

A function is a named block of code that does one job. You write it once and then call it (use it) as many times as you like. You've already used one: main!

Think of it like this: A function is like a coffee machine. You don't need to know what happens inside. You press the button (call the function) and coffee comes out. You can press it again and again.

Your first function

#include <iostream>
using namespace std;

void sayHello() {
    cout << "Hello!\n";
    cout << "Welcome to C++.\n";
}

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

Output

Hello!
Welcome to C++.
Hello!
Welcome to C++.
  • void means the function doesn't give back any value. It just does something.
  • sayHello is the name, followed by ().
  • The code in { } is the function body.
  • sayHello(); inside main calls it. Each call runs the whole body.

Remember: C++ reads your file from top to bottom, so write a function above the place where you call it.

Declaring first, defining later

If you prefer to keep main at the top, write just the function's first line with a semicolon – a declaration (also called a prototype) – and put the full function below:

#include <iostream>
using namespace std;

void drawLine();          // declaration: "this function exists"

int main() {
    drawLine();
    cout << "  Menu\n";
    drawLine();
    return 0;
}

void drawLine() {         // definition: what it actually does
    cout << "----------\n";
}

Output

----------
  Menu
----------
HOME LABS COMMUNITY DASHBOARD