In C++, a function is a group of statements that performs a specific task. Functions are used to organize code, improve code reusability, and reduce code duplication. To create a simple function in C++, you need to define the function signature, which includes the function name, parameter list, and return type, and then implement the function body. Here’s an example of a simple function that calculates the sum of two integers:
int sum(int a, int b) {
return a + b;
}
int main() {
int result = sum(3, 5);
std::cout << "Result is: " << result << std::endl; // prints 8
return 0;
}
In this example, the sum() function takes two integer parameters, a and b, and returns their sum. The main() function calls the sum() function with arguments 3 and 5 and assigns the result to a variable called result. Finally, the result is printed to the console using std::cout.
To define a function, you need to follow these steps:
Define the function signature: This includes the function name, parameter list, and return type. For example:
int sum(int a, int b);
This declares a function called sum() that takes two integer parameters and returns an integer.
Implement the function body: This includes the statements that perform the task of the function. For example:
int sum(int a, int b) {
int result = a + b;
return result;
}
This defines a function called sum() that takes two integer parameters, calculates their sum and assigns the result to a variable called result, and finally returns the result.
Call the function: To call a function, you simply use its name followed by its arguments in parentheses. For example:
int myResult = sum(3, 5);
This calls the sum() function with arguments 3 and 5, and assigns the result to a variable called myResult.
In summary, to create a simple function in C++, you need to define the function signature, which includes the function name, parameter list, and return type, and then implement the function body. Once the function is defined, you can call it from other parts of the program to perform a specific task.