Function in C++

A function is a block of code that performs a specific task or set of tasks. Functions are used to organize code into modular and reusable units. They help in breaking down a large program into smaller, more manageable pieces, making it easier to understand, maintain, and debug.

Key characteristics of functions

Name: A function has a name that uniquely identifies it within a program. The name is used to call (invoke) the function when needed.
Parameters: Functions can take input values called parameters. These parameters are used as variables inside the function and provide a way to pass information into the function.
Return Type: A function may return a value after it completes its task. The return type specifies the type of the value that the function will return. If a function does not return a value, the return type is typically set to void.
Body: The body of a function contains a set of statements that define what the function does. These statements are executed when the function is called.
Function Call: To execute the code within a function, you need to call the function by using its name along with any required arguments (values passed to the parameters).

Syntax

// Function Declaration
returnType functionName(parameterType1 paramName1, parameterType2 paramName2, ...);
// Function Definition
returnType functionName(parameterType1 paramName1, parameterType2 paramName2, ...) {
    // Function Body
    // Statements to perform the task
    return returnValue; // Optional return statement
}
Example
#include<iostream>
// Function Declaration
int add(int a, int b);
int main() {
    // Function Call
    int result = add(3, 4);
    // Output the result
    std::cout << "Sum: " << result << std::endl;
    return 0;
}
// Function Definition
int add(int a, int b) {
    return a + b;
}

Function Prototypes

In larger programs, you may need to declare functions before using them to inform the compiler about the function's existence. This is known as a function prototype.

// Function Prototype
int add(int a, int b);
int main() {
    // Function Call
    int result = add(3, 4);
    // Output the result
    std::cout << "Sum: " << result << std::endl;
    return 0;
}
// Function Definition
int add(int a, int b) {
    return a + b;
}

Default Arguments

You can also provide default values for function parameters:

int multiply(int a, int b = 2) {
    return a * b;
}
int main() {
    std::cout << "Product: " << multiply(5) << std::endl; // Uses default value for b
    std::cout << "Product: " << multiply(5, 3) << std::endl; // Uses provided value for b
    return 0;
}

Recursive Functions

A function can call itself, which is known as a recursive function.
int factorial(int n) {
    if (n <= 1)
        return 1;
    else
        return n * factorial(n - 1);
}