Instagram
youtube
Facebook
Twitter

Functions in C++

Functions in C++

In C++, functions are used to encapsulate a set of instructions that perform a specific task. Functions help modularize code, making it more systematised, applicable, and easily understood. Then there is an overview of how functions work in C++.

  • Function Protestation: A function protestation specifies the name of the function, its return type, and the types of its parameters (if any). The protest generally appears before the function is used.

Example:

#include <iostream>

using namespace std;

void greet();  

int add(int a, int b);  

int main() {

    greet();  

    int sum = add(3, 5);

    cout << "Sum: " << sum << endl;

    return 0;

}

void greet() {

    cout << "Hello! Welcome to the C++ world!" << endl;

}

int add(int a, int b) {

    return a + b;

}
  • Function Definition:A function definition provides the implementation of the function. It includes the function body, which contains the instructions that are executed when the process is called.

 

Example:

#include <iostream>

using namespace std;

void greet() {

    cout << "Hello! Welcome to the C++ world!" << endl;

}

int add(int a, int b) {

    return a + b;

}

double divide(double a, double b = 1.0) {

    if (b != 0) {

        return a / b;

    } else {

        cout << "Error: Division by zero!" << endl;

        return 0.0;

    }

}

int main() {

    greet();  

     int sum = add(3, 5); 

    cout << "Sum: " << sum << endl;


    double result1 = divide(10.0, 2.0);

    double result2 = divide(8.0);  

    cout << "Division Result 1: " << result1 << endl;

    cout << "Division Result 2: " << result2 << endl;

    return 0;

}
  • Function Call:To execute a function and obtain its result, you need to call the function. The function call consists of the function name followed by parentheses and any necessary arguments inside the parentheses.

Example:

#include <iostream>

using namespace std;

void greet() {

    cout << "Hello! Welcome to the C++ world!" << endl;

}

int add(int a, int b) {

    return a + b;

}

int main() {

    greet();  

    int sum = add(3, 5);  

    cout << "Sum: " << sum << endl;

    return 0;

}
  • Return Statement:The return statement is used to return a value from a function back to the caller. It terminates the function’s execution and returns the specified value. The return type in the function declaration must match the type of the value being returned.

Example:

#include <iostream>

using namespace std;

int add(int a, int b) {

    return a + b;  

}

void greet() {

    cout << "Hello! Welcome to the C++ world!" << endl;

    return;  

}

int main() {

    int result = add(3, 5);

    cout << "Sum: " << result << endl;

    greet();

    return 0;

}
  • Function Overloading:C++ allows you to define multiple functions with the same name but different parameter lists. This is called function overloading. The compiler determines which function to call based on the number, types, and order of the arguments passed.

Example:

#include <iostream>

using namespace std;

int add(int a, int b) {

    return a + b;

}

double add(double a, double b) {

    return a + b;

}

int add(int a, int b, int c) {

    return a + b + c;

}

int main() {

    int result1 = add(3, 5);           

   double result2 = add(2.5, 3.7);  

    int result3 = add(1, 2, 3);      

    cout << "Result 1: " << result1 << endl;

    cout << "Result 2: " << result2 << endl;

    cout << "Result 3: " << result3 << endl;

    return 0;

}
  • Recursion:In C++, a function can call itself. This is known as recursion. Recursion is useful for solving problems that can be divided into smaller sub-problems. Still, it requires careful design to ensure proper termination conditions to avoid horizonless recursion.

Example:

#include <iostream>

int factorial (int n){

if (n == 0 || n == 1) {

return 1;

}

return n * factorial(n - 1);

}

int main() {

int number = 5;

int result = factorial(number);

std::cout << "factorial of" << number << "is" << result << std::endl;

return 0;

}

Lambda Functions:

A lambda function in C++ is an anonymous, inline function that can be defined directly within the code. Lambda functions provide a concise way to create small, local functions without the need for a separate function declaration or definition. Lambda functions are often used when a short, simple function is needed for a specific task.

Here’s the basic syntax of a lambda function:

[capture](parameters) -> return_type {


    }
  • ‘capture’ specifies what variables from the surrounding scope the lambda function can access. You can capture variables by value(‘[x]’) or by reference (‘[x]’), or use a mix of both. The capture clause is optional if the lambda doesn’t need access to external variables.
  • Parameters are the input parameters, similar to those of a regular function, defined inside the parentheses (parameters). You can omit the parameter list if the lambda does not take any arguments.
  • ‘return_type’ is the type of the lambda that is specified after the parameter list using the arrow operator ->. Still, the arrow operator and return type can be omitted if the return type can be deduced from the lambda’s body.
  • ‘Function body’ contains the actual code that the lambda will execute. This can be a single expression or a block of statements enclosed in curly braces ‘{}’.

Here’s an example of using lambda functions:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main() {

    vector<int> numbers = {5, 2, 8, 1, 9, 3};

       sort(numbers.begin(), numbers.end(), [](int a, int b) {

        return a < b;

    });

    cout << "Sorted Numbers: ";

    for_each(numbers.begin(), numbers.end(), [](int num) {

        cout << num << " ";

    });

    cout << endl;

    int sum = 0;

 for_each(numbers.begin(), numbers.end(), [&sum](int num) {

        sum += num;

    });

    cout << "Sum: " << sum << endl;

    return 0;

}

These are the basics of functions in C++. Functions can be used to perform colorful operations and calculations, improve code organisation, and promote code reusability.