Functions and Modules
Functions are blocks of code that perform a specific task. They allow us to break down our program into smaller, manageable parts, making the code more readable and modular. In C++, we can define our own functions and call them whenever needed.
Function Declaration and Definition
To create a function, we need to declare and define it. The declaration consists of specifying the function name, return type, and parameters (if any). The definition contains the actual code of the function.
Here's an example of a function declaration and definition:
1// Function declaration
2int add(int a, int b);
3
4int main() {
5 // Function call
6 int result = add(5, 3);
7 cout << "The sum is: " << result << endl;
8 return 0;
9}
10
11// Function definition
12int add(int a, int b) {
13 return a + b;
14}
In the above code, we declare a function named add
that takes two integer parameters a
and b
and returns an integer. The function definition contains the logic of adding the two parameters and returning the result.
Function Call
To execute a function, we need to call it. Function calls are made by specifying the function name followed by parentheses. If the function has parameters, we need to pass the values inside the parentheses.
In the example code, we call the add
function with arguments 5
and 3
, and the returned value is stored in the result
variable. We then print the result using the cout
statement.
Feel free to create your own functions and call them as needed. Breaking down code into smaller functions can make it easier to write and maintain complex programs.
xxxxxxxxxx
using namespace std;
// Function declaration
int add(int a, int b);
int main() {
// Function call
int result = add(5, 3);
cout << "The sum is: " << result << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}