C++ ยท Chapter 26 of 49

C++ Functions

A function is a reusable named block of code with a return type, a name, and a parameter list, e.g. `int add(int a, int b) { return a + b; }`. Functions must be declared (or defined) before they're called, or you need a forward declaration.

Breaking a program into functions improves readability, avoids repetition, and makes testing individual pieces easier.

Defining and calling

A function definition specifies its return type, name, and parameters. Calling it with matching arguments executes the body and returns a value via `return`.

void functions

A function that returns nothing uses `void` as its return type and simply ends without a `return value;` statement (a bare `return;` is optional).

Example 1 (cpp)
int add(int a, int b) {
    return a + b;
}
int main() {
    std::cout << add(2, 3);
}
Output
5

add() takes two ints and returns their sum.

Example 2 (cpp)
void greet() {
    std::cout << "Hi!";
}
int main() { greet(); }
Output
Hi!

void functions don't return a value.

Key points

  • Functions have a return type, name, and parameters.
  • void means the function returns nothing.
  • Functions must be declared before use (or forward-declared).
  • Breaking code into functions improves reuse and clarity.
๐Ÿ’ก Note: Header files typically hold function declarations while .cpp files hold their definitions in larger projects.

๐Ÿ“ Quick Quiz

1. What return type means a function returns nothing?

2. What keyword sends a value back from a function?

3. Why use functions?