Functions in C++
In C++, a function is a block of code that performs a specific task. Functions are used to break down a program into smaller and more manageable pieces, making the code more organized and modular.
Defining a Function
To define a function in C++, you need to specify the function's return type, name, and parameters (if any). The return type indicates the data type of the value that the function returns, if any.
Here's an example of a function that calculates and returns the sum of two numbers:
1// Function to add two numbers
2int add(int a, int b) {
3 return a + b;
4}
In the code above, the function add
takes two integer parameters a
and b
and returns their sum.
Calling a Function
To call a function in C++, you need to use the function name followed by parentheses. If the function has parameters, you need to provide the values for the parameters.
Here's an example of calling the add
function from the previous example:
1int num1 = 5;
2int num2 = 10;
3int sum = add(num1, num2);
In the code above, the add
function is called with the values of num1
and num2
as arguments, and the returned sum is stored in the variable sum
.
Output
The console output of the above example will be:
1The sum of 5 and 10 is: 15
xxxxxxxxxx
using namespace std;
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
int main() {
int num1 = 5;
int num2 = 10;
int sum = add(num1, num2);
cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << endl;
return 0;
}