Skip to content
Home » C++ Local Functions

C++ Local Functions

    A function is declared globally above the main function, or within the main function. You can also declare a function inside another function in C++. In this article, you will learn to declare, define and call a local function.

    Local Function Declaration

    Like every other function, a local function must be declared within the body of another function. You must declare the return type, number of parameters and their type.

    For example,

    void account()
    
    {
    
        int total;
    
        int bill1, bill2;
    
        int add_bills(int , int );
    
    //Initialization of variables
    
        bill1 = 2000;
    
        bill2 = 5000;
    
        total = 0;
    
    //Compute total bill amount
    
        total = add_bills( bill, bill2);
    
    //Print results
    
        cout << "Total Amount =" << "" << total << endl;
    
    }
    
    //Definition of function add_bills()
    
    int add_bills( int bill1, int bill2)
    {
    
        return(bill1 + bill2);
    
    }

    The function add_bills() is a local function with proper declaration, definition and function call. The function add_bills() adds the bill1 and bill2 and return their sum.

    You can add any number of local functions in your program as long as they do not violate the rules of C++ functions.

    Recursive Functions

    The recursive function is a special case of local function where a function calls itself several times until the programming problem is solved.

    See the following figure for the general structure of a recursive function.

    Recursive Function
    Recursive Function

    The function factorial calls itself recursively because each call to factorial will also call itself until the value of n becomes 0. The value of n is decreasing with each iteration.

    Example Program:

    /*Program to compute Nth factorial */
    
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int fact (int n)
    {
    
        unsigned int f;
    
        if ((n == 0) || (n == 1))
    
            return (n);
    
        else
    
            /* Compute factorial by Recursive calls */
    
            f = n * fact (n - 1); 
    
            return (f);
    
    }
    
    main ()
    {
    
        int i, n;
    
        /* Reading the number */
    
        cout << "Enter the Number :";
    
        cin >> n;
        
        /* Printing results */
    
        cout << "Factorial of Number" << n <<" is " << fact (n) << endl;
    
       
        system ("PAUSE");
    
        return 0;
    
    }
    

    Output:

    Enter the Number: 5
    Factorial of Number 5 is 120