What is function in C++?

In C++, a function (also known as a procedure or subroutine in other programming languages) is a fundamental building block used to perform specific tasks. Functions enable modular programming by allowing code to be organized into reusable, manageable units.

Advantages of Functions in C++

1. Code Reusability:

Functions allow you to define a block of code once and reuse it multiple times throughout your program. This eliminates the need for repetitive code and simplifies program maintenance. For instance, if you need to perform a specific operation, you can call the function whenever required rather than rewriting the code each time.

2. Code Optimization:

By using functions, you can optimize your code. Functions help in organizing and streamlining code, making it more efficient. They reduce redundancy and the potential for errors by encapsulating logic in a single location. This also makes the code easier to debug and understand.

Types of Functions

1. Library Functions:

These are predefined functions provided by the C++ standard library or other libraries included in the program. They perform common tasks and can be used directly without needing to define them. Examples include mathematical functions like ceil(x), cos(x), and exp(x) which are declared in standard header files.

2. User-Defined Functions:

These are functions that programmers create to perform specific tasks. User-defined functions help in reducing complexity by breaking down large programs into smaller, manageable pieces. They allow for code modularity and reuse, making programs easier to manage and understand.

Example:

<#include <iostream>>
using namespace std;

// Function declaration
int addNumbers(int a, int b);

int main() {
int num1, num2, sum;

cout << "Enter first number: " << endl;
cin >> num1;
cout << "Enter second number: " << endl;
cin >> num2;

// Function call
sum = addNumbers(num1, num2);

cout << "The sum is: " << sum << endl;

return 0;
}

// Function definition
int addNumbers(int a, int b) {
return a + b;
}

Output:

Enter first number: 10
Enter second number: 20
The sum is: 30

Explanation:

1. Function Declaration:

• int addNumbers(int a, int b);

• This line tells the compiler that there is a function named addNumbers that takes two integers as arguments and returns an integer.

2. Function Definition:

• int addNumbers(int a, int b) { return a + b; }

• This is where the actual implementation of the function is provided. It takes two integer parameters, adds them, and returns the result.

3. Function Call:

• sum = addNumbers(num1, num2);

• In the main function, addNumbers is called with num1 and num2 as arguments. The result is stored in the variable sum.

4. Output:

• The program will prompt the user to enter two numbers, add them using the addNumbers function, and display the result.