0% found this document useful (0 votes)
16 views11 pages

4. Function

The document provides an overview of C++ functions, including their types (standard library and user-defined), declaration syntax, parameters, return statements, and prototypes. It covers function call types (call by value, pointer, and reference), recursion, default arguments, function overloading, and inline functions. Additionally, it highlights the benefits and drawbacks of using recursion in programming.

Uploaded by

tomjerry02323
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views11 pages

4. Function

The document provides an overview of C++ functions, including their types (standard library and user-defined), declaration syntax, parameters, return statements, and prototypes. It covers function call types (call by value, pointer, and reference), recursion, default arguments, function overloading, and inline functions. Additionally, it highlights the benefits and drawbacks of using recursion in programming.

Uploaded by

tomjerry02323
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

C++ Function

A function is a block of code that performs a specific task.


Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
There are two types of function:
Standard Library Functions: Predefined in C++
User-defined Function: Created by users
C++ allows the programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code is given a
name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined in the
body of the function.
C++ Function Declaration
The syntax to declare a function is:
returnType functionName (parameter1, parameter2,...)
{
// function body
}
Example 1: Display a Text
#include <iostream>
using namespace std;
// declaring a function
void greet()
{
cout << "Hello there!";
}
int main()
{
// calling the function
greet();
return 0;
}
Output
Hello there!
Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function.
Example 2: Function with Parameters
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2)
{
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main()
{
int num1 = 5;
double num2 = 5.5;

1
// calling the function
displayNum(num1, num2);
return 0;
}
Output
The int number is 5
The double number is 5.5
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.

Return Statement
It's also possible to return a value from a function. For this, we need to specify the return Type of the
function during function declaration.
Then, the return statement can be used to return a value from a function.
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>
using namespace std;
int add(int a, int b)
{
return (a + b);
}
int main()
{
int x, y, sum;
cout<<”enter the value of a and b:”
cin>>a>>b;
// calling the function and storing
// the returned value in sum
sum = add(x, y);
cout << "a+b= " << sum << endl;
return 0;
}
Output
Enter the value of a and b:10
20
a+b = 30
Note: in the above example a and b are known as formal parameters and x and y are known as
actual parameters.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we want to
define a function after the function call, we need to use the function prototype.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
Example 4: C++ Function Prototype
#include <iostream>
using namespace std;
// function prototype
int add(int, int);
int main()
{

2
int sum;
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
// function definition
int add(int a, int b)
{
return (a + b);
}
Output
100 + 78 = 178

Benefits of Using User-Defined Functions


Functions make the code reusable. We can declare them once and use them multiple times.
Functions make the program easier as each small task is divided into a function.
Functions increase readability.
C++ Library Functions
Library functions are the built-in functions in C++ programming.
Programmers can use library functions by invoking the functions directly; they don't need to write
the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which these library
functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the
header file cmath.
Example 5: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5

Pointers and references:


Pointer:
A pointer is a variable whose value is the address of another variable. Like any variable or constant,
you must declare a pointer before you can work with it. The general form of a pointer variable
declaration is
type *var-name;
Example:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float

3
char *ch // pointer to character
Example1:
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Output
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Reference:
A reference variable is an alias, that is, another name for an already existing variable. Once a
reference is initialized with a variable, either the variable name or the reference name may be used
to refer to the variable.
Example:
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Example1:
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Output:
Value of i : 5
Value of i reference : 5

4
Value of d : 11.7
Value of d reference : 11.7

Function call types:


1 Call by Value
This method copies the actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no effect on the argument.
Example:
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
// function definition to swap the values.
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
2 Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.
Example:
#include <iostream>
using namespace std;
// function declaration
void swap(int *x, int *y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;

5
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
// function definition to swap the values.
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that changes made to
the parameter affect the argument.
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Before swap, value of a :100
Before swap, value of b :200

6
After swap, value of a :200
After swap, value of b :100

Return by reference:
In C++ Programming, not only can you pass values by reference to a function but you can also return
a value by reference.
Example:
#include <iostream>
using namespace std;
int& max(int& x, int& y);
int main()
{
int a=10,b=20;
cout<< "Enter the value of a and b:";
cin>>a>>b;
max(a,b) = -1;
cout <<"a="<<a<<"\nb="<<b;
return 0;
}
int& max(int& x,int& y)
{
if(x>y)
return x;
else
return y;
}
Output
Enter the value of a and b:10
20
a=10
b=-1
Note: Ordinary function returns value but this function doesn't. Hence, you cannot return a constant
from the function.
int& test()
{
return 2;
}
You cannot return a local variable from this function.
int& test()
{
int n = 2;
return n;
}

Recursion:
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
The recursion continues until some condition is met.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call and the other doesn't.

7
void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output

Enter a non-negative number: 4


Factorial of 4 = 24
Advantages of C++ Recursion
• It makes our code shorter and cleaner.
• Recursion is required in problems concerning data structures and advanced algorithms, such
as Graph and Tree Traversal.
Disadvantages of C++ Recursion
• It takes a lot of stack space compared to an iterative program.
• It uses more processor time.
• It can be more difficult to debug compared to an equivalent iterative program.

8
Default Arguments (Parameters):
we can provide default values for function parameters.
If a function with default arguments is called without passing arguments, then the default
parameters are used.
However, if arguments are passed while calling the function, the default arguments are ignored.
Example:
#include <iostream>
using namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
void display(char c, int count) {
for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
Note:
• Once we provide a default value for a parameter, all subsequent parameters must also have
default values.
• If we are defining the default arguments in the function definition instead of the function
prototype, then the function must be defined before the function call.

Function Overloading:
Two functions can have the same name if the number and/or type of arguments passed is different.
Example:
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Example1:
#include <iostream>

9
using namespace std;

void display(int var1, double var2)


{
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
void display(double var)
{
cout << "Double number: " << var << endl;
}
void display(int var)
{
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5;
double b = 5.5;
// call function with int type parameter
display(a);
// call function with double type parameter
display(b);
// call function with 2 parameters
display(a, b);
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5

Inline Function:
To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An
inline function is a function that is expanded inline when it is invoked. That is the compiler replaces
the function call with the corresponding function code.
The inline functions are defined as follows: -
inline function-header
{
function body;
}
Example:
inline double cube (double a)
{
return(a*a*a);
}
The above inline function can be invoked by statements like c=cube(3.0);
d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the compiler. The
compiler may ignore this request if the function definition is too long or too complicated and
compile the function as a normal function.

10
Some of the situations where inline expansion may not work are:
1. For functions returning values if a loop, a switch or a go to exists.
2. for functions not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive.
Example:
#include<iostream.h> #include<stdio.h>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p.double q)
{
return(p/q);
}
main( )
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
}
output
121.227898
1.257128

The benefits of inline functions


• Better than macros
• Function call overheads are eliminated
• Program become more readable
• More executes more efficiently

Constant Argument:
In C++,an argument to a function can be declared as unit as const as shown below.
int strlen(const char *p);
int length(const string &s);
The qualifier const tells the compiler that the function should not modify the argument. The
compiler will generate an error when this condition is violated. This type of declaration is significant
only when we pass arguments by reference or pointers.

11

You might also like