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:
#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
returnstatement (e.g.int,double,bool). If the function does not return any value, the special typevoidis used. - Name: the identifier to call the function (using
camelCasestyle 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):
#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
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.
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
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.
Show hint
La funzione deve restituire un tipo `bool`. Usa `n % 2 == 0`.
Solution available after 3 attempts