Skip to main content
eLearner.app
Module 3 · Lesson 1 of 27/18 in the course~10 min
Module lessons (1/2)

Basic functions

Functions allow organizing code into reusable logical blocks, reducing duplication and improving readability.

In C++, every function must declare the type of value it returns, its name, and the types of the parameters it accepts.

Defining a Function

Here is an example of a simple function that sums two integers:

Code
#include <iostream>

// Function definition
int add(int a, int b) {
    return a + b; // Returns the sum
}

int main() {
    int result = add(3, 4); // Function call
    std::cout << "Result: " << result << std::endl;
    return 0;
}

Structure and Signature

  • Return Type: the type of the value returned with the return statement (e.g. int, double, bool). If the function does not return any value, the special type void is used.
  • Name: the identifier to call the function (using camelCase style in accordance with R2).
  • Parameters: the list of input variables enclosed in parentheses (), each preceded by its type.

Declaration vs Definition

To place functions below the main function, you first declare the prototype (the signature without the body):

Code
#include <iostream>

// Prototype (Declaration)
int multiply(int a, int b);

int main() {
    std::cout << multiply(3, 5); // Valid
    return 0;
}

// Definition
int multiply(int a, int b) {
    return a * b;
}

Try it yourself

Exercise#cpp.m3.l1.e1
Attempts: 0Loading…

Define a function named square that takes an integer n and returns its square (n * n). Call it inside main to calculate the square of 5 and print it using std::cout.

Loading editor…
Show hint

La firma della funzione è `int square(int n)`. Ricorda di posizionare la definizione della funzione prima del `main`.

Solution available after 3 attempts

Exercise#cpp.m3.l1.e2
Attempts: 0Loading…

Define a boolean function named isEven that takes an integer n and returns true if the number is even (using % 2 == 0), otherwise false. Call it in main with 4 and print it.

Loading editor…
Show hint

La funzione deve restituire un tipo `bool`. Usa `n % 2 == 0`.

Solution available after 3 attempts