Introduction to Functions in C++

Welcome to our lesson on C++ functions! Functions form the building blocks of any program by encapsulating chunks of code into reusable modules, which are key to constructing complex code. Let's explore further!

Understanding Functions

Have you ever used a recipe? If so, you've employed a real-world function, albeit an ad hoc one. A function is a set of instructions designed to accomplish a specific task. Functions help package blocks of code into reusable components, a concept known as code reusability.

Function Syntax and Definition

Every C++ function consists of a name, a return type, and a parameter list, forming the following syntax:

return_type function_name( parameter list ) {
   // function body
}

Let's break down each part.

Function: Example 1

Let's consider a function without arguments that prints a greeting in the console. It doesn't take any parameters, and a void return type specifies it doesn't return a value.

Example function:

void greet() {
    std::cout << "Hello, C++ learner!" << std::endl;
}

Example function call:

#include <iostream>

int main() {
    greet();  // Hello, C++ learner!
    return 0;
}

While this function might seem not very useful, it already brings out the most significant advantage of using function: reusability! We can call this function as many times as we want without rewriting its code:

#include <iostream>

int main() {
    greet();  // Hello, C++ learner!
    greet();  // Hello, C++ learner!
    greet();  // Hello, C++ learner!
    return 0;
}
Function: Example 2

Let's consider a function with arguments, which can accept parameters, It will still have a void return type, meaning it doesn't return a value.

Example function:

void greet(string name) {
    std::cout << "Hello, " << name << "!" << std::endl;
}

This function prints out a personalized greeting, using the provided name. Here is an example code:

#include <iostream>
#include <string>

int main() {
    greet("Bob");  // Hello, Bob!
    greet("Alice");  // Hello, Alice!
    greet("C++ learner");  // Hello, C++ learner!
    return 0;
}

Now, our program is more friendly!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal