C++ Fonctions avec exemples de programmes
What is a Function in C++?
A fonction in C++ refers to a group of statements that takes input, processes it, and returns an output. The idea behind a function is to combine common tasks that are done repeatedly. If you have different inputs, you will not write the same code again. You will simply call the function with a different set of data called parameters.
Chaque projet rรฉcompensรฉ par un C++ le programme a au moins une fonction, la fonction main(). Vous pouvez diviser votre code en diffรฉrentes fonctions. Cette division doit รชtre telle que chaque fonction accomplisse une tรขche spรฉcifique.
There are many built-in functions in the C++ standard library. You can call these functions within your program.
Pourquoi utiliser des fonctions ?
There are numerous benefits associated with the use of functions. These include:
- Each function puts related code together. This makes it easier for programmers to understand code.
- Functions make programming easier by eliminating code repetition.
- Functions facilitate code reuse. You can call the same function to perform a task at different sections of the program or even outside the program.
Fonctions intรฉgrรฉes
In C++ library functions are built-in C++ functions. To use these functions, you simply invoke/call them directly. You do not have to write the functions yourself.
Exemple 1:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num, squareRoot;
cout << "Enter number: ";
cin >> num;
squareRoot = sqrt(num);
cout << "The square root of " << num << " is: " << squareRoot;
return 0;
}
Sortie :
Voici une capture d'รฉcran du code :
Code Explication:
- Incluez le fichier d'en-tรชte iostream dans notre programme pour utiliser ses fonctions.
- Include the cmath library to use its functions. We want to use the function sqrt() defined in it.
- Incluez l'espace de noms std dans notre code pour utiliser ses classes sans l'appeler.
- Appelez la fonction main(). La logique du programme doit รชtre ajoutรฉe dans le corps de cette fonction.
- Declare two double variables, num, and squareRoot.
- Print some text on the console. The text asks the user to enter a number.
- Read user input from the keyboard. The input will become the value of variable num.
- Call the library function sqrt(), which calculates the square root of a number. We passed the parameter num to the function, meaning it will calculate the square root of num. This function is defined in the cmath library.
- Print the number entered by the user, its square root, and some other text on the console.
- Le programme doit renvoyer de la valeur une fois terminรฉ.
- Fin du corps de la fonction main().
User-Defined Functions
C++ allows programmers to define their own functions. The purpose of the function is to group related code. The code is then given a unique identifier, the function name.
The function can be called/invoked from any other part of the program. It will then execute the code defined within its body.
Exemple 2:
#include <iostream>
using namespace std;
void sayHello() {
cout << "Hello!";
}
int main() {
sayHello();
return 0;
}
Sortie :
Voici une capture d'รฉcran du code :
Code Explication:
- Incluez le fichier d'en-tรชte iostream dans notre programme pour utiliser ses fonctions.
- Incluez l'espace de noms std dans notre code pour utiliser ses classes sans l'appeler.
- Create a user-defined function named sayHello().
- Print some text on the console when the sayHello() function is called.
- End of the body of the sayHello() function.
- Appelez la fonction main(). La logique du programme doit รชtre ajoutรฉe dans le corps de cette fonction.
- Call/invoke the function named sayHello().
- Le programme doit renvoyer de la valeur une fois terminรฉ.
- Fin du corps de la fonction main().
Function Declaration/Prototype
If you define a user-defined function after the main() function, the C++ compilateur renverra une erreur. La raison en est que le compilateur ne connaรฎt pas les dรฉtails de la fonction dรฉfinie par l'utilisateur. Les dรฉtails incluent son nom, les types d'arguments et leurs types de retour.
In C++, the function declaration/prototype declares a function without a body. This gives the compiler details of the user-defined function.
In the declaration/prototype, we include the return type, the function name, and argument types. The names of arguments are not added. However, adding the argument names generates no error.
Dรฉfinition de la fonction
Le but de la dรฉclaration de fonction est d'indiquer au C++ compiler about the function name, the return type, and parameters. A function definition tells the C++ compiler about the function body.
Syntaxe
return_datatype function_name( parameters) {
function body
}
Dโaprรจs ce qui prรฉcรจde, une dรฉfinition de fonction comporte lโen-tรชte et le corps de la fonction. Voici une explication des paramรจtres :
- return_datatype- Some functions return value. This parameter denotes the data type of the return value. Some functions donโt return value. In that case, the value of this parameter becomes void.
- function_name- This is the name of the function. The function name and parameters form the function signature.
- Parameters- This is the type, the order, and the number of function parameters. Some functions donโt have parameters.
- function body- these are statements defining what the function will do.
Function Call
For a function to perform the specified task and return output, it must be called. When you call a function, it executes the statements added within its body.
A program is called by its name. If the function takes parameters, their values should be passed during the call. If the service takes no parameters, donโt pass any value during the call.
Passer des arguments
In C++, un argument/paramรจtre correspond aux donnรฉes transmises ร une fonction lors de son appel. Les valeurs doivent รชtre initialisรฉes ร leurs variables respectives.
When calling a function, the arguments must match in number. The means the values you pass must be equal to the number of parameters. Again, the values must also match the parameters in terms of type. If the first parameter is an integer, the value passed to it must be an integer.
One can assign default values to function parameters. If you donโt pass a value for the parameter during the function call, the default value will be used.
Example 3: How to Write and Call a Function
#include <iostream>
using namespace std;
int addFunc(int, int);
int main() {
int x, y, sum;
cout << "Enter two numbers: ";
cin >> x >> y;
sum = addFunc(x, y);
cout <<"The sum of "<<x<< " and " <<y<<" is: "<<sum;
return 0;
}
int addFunc(int num1, int num2) {
int addFunc;
addFunc = num1 + num2;
return addFunc;
}
Sortie :
Voici une capture d'รฉcran du code :
Code Explication:
- Incluez le fichier d'en-tรชte iostream dans notre programme pour utiliser ses fonctions.
- Incluez l'espace de noms std dans notre code pour utiliser ses classes sans l'appeler.
- Declare a function named addFunc() that takes two integer parameters. This creates the function prototype.
- Appelez la fonction main(). La logique du programme doit รชtre ajoutรฉe dans le corps de cette fonction.
- Declare three integer variables, x, y, and sum.
- Print some text on the console. The text asks the user to enter two numbers.
- Read the user input from the keyboard. The user should enter two numbers for variables x and y, separated by space.
- Call the function addFunc() and passing to it the parameters x and y. The function will operate on these parameters and assign the output to the variable sum.
- Print the values of variables x, y, and sum on the console alongside other text.
- La fonction doit renvoyer une valeur une fois terminรฉe avec succรจs.
- Fin du corps de la fonction main().
- Function definition. We are defining the function addFunc(). We will state what the function will do within its body, the { }.
- Declaring an integer variable named addFunc.
- Adding the values of parameters num1 and num2 and assigning the result to variable addFunc.
- The addFunc() function should return the value of addFunc variable.
- End of the function body, that is, function definition.
Rรฉsumรฉ
- A function in C++ helps you group related code into one.
- Functions facilitate code reuse.
- Au lieu dโรฉcrire encore et encore du code similaire, vous le regroupez simplement dans une fonction. Vous pouvez ensuite appeler la fonction depuis n'importe oรน dans le code.
- Functions can be library or user-defined.
- Library functions are the functions built-in various C++ fonctions.
- To use library functions, you simply include its library of definition and call the function. You donโt define the function.
- User-defined functions are the functions you define as a C++ programmeur.
- A function declaration tells the compiler about the function name, return type, and parameter types.
- A function definition adds the body of the function.
- If a function takes parameters, their values should be passed during the function call.






