Functions are a fundamental building block of C++ programs. They allow you to encapsulate reusable pieces of code and make your programs more modular and easier to understand.
In C++, a function is typically declared before it is used, and defined later in the program. The general syntax for declaring and defining a function is as follows:
return_type function_name(parameter_list) {
// Function body
}Example of a function declaration and definition:
// Declaration
int add(int a, int b);
// Definition
int add(int a, int b) {
return a + b;
}In this example, we declare a function named `add` that takes two integer parameters and returns their sum. Later in the program, we define the function's behavior.
To call a function in C++, simply use its name followed by parentheses and any required arguments. The function returns control to the caller once it has completed execution.
Example of calling a function:
int result = add(5, 3); // result is now 8
In this example, we call the `add` function with arguments `5` and `3`, and store the result in the variable `result`.
Functions can have parameters, which are variables used to pass values to the function. They can also have a return type, specifying the type of value the function will return to the caller.
Example of a function with parameters and return value:
int add(int a, int b) {
return a + b;
}In this example, the `add` function takes two integer parameters `a` and `b`, and returns their sum as an integer.
Function overloading allows you to define multiple functions with the same name but different parameter lists or return types. This can make your code more expressive and easier to use.
Example of function overloading:
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}In this example, we define two `add` functions - one that takes two integers and returns their sum as an integer, and another that takes two floats and returns their sum as a float.