# 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.

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


Bestseller

Object-Oriented Programming with C++ – 8th Edition

Object-oriented programming with C++, 8th edition is here with some valuable updates. The new edition helps students to assess their learning by answering questions based on learning outcomes. Objective-type questions and dry-run questions are introduced to make students exam ready. A new appendix on interview questions is for those seeking to join the industry. The book is designed for students studying at the undergraduate level. It provides all-inclusive concepts and programs on object-oriented programming with C++ as an implementation language.

• 150+ multi-choice questions
• 100+ dry-run exercises
• 90+ interview questions
• Two new projects and more