C++ Programming
SLO # 14
Functions
By Younus Bashir
What is C++ function?
Function is a logically grouped set of statements that perform
a specific task. In C program, a function is created to achieve
something. Every C program has at least one function
i.e. main() where the execution of the program starts.
It is a mandatory function in C++.
The advantages of using functions are:
easily managed in case of functions
Functions make code modular. Consider a big file having many
lines of codes.
It becomes really simple to read and use the code if the code is
divided into functions.
Functions provide abstraction.
For example, we can use library functions without worrying about
their internal working.
Built-in function:
Built-in functions are the functions that are provided by any
language library. In the programming world, many activities are
done by using a built-in function. A library function is accessed
simply by writing the function name, followed by an optional list of
arguments.
Explanation:
Every function has a predefined task that it can perform in the
program. The programmer has to include the concerned library file
(header file) while using a pre-defined function according to the
Requirement. These functions are also called built-in function.
Function | Purpose/ example | Argument(s) | Return |
abs(x) | Return the absolute value of its integer number: if x is -5,abs(-5) is 5 | int | int |
abs(x) | Return the absolute value of its double number: if x is -5.2,abs(-5.2) is 5.2 | Double | Double |
log(x) | Return the natural algorithm of x for x | Double | Double |
pow(x,y) | Returns x^y. | Double/int | Double/int |
sqrt(x) | Return the non-negative square root of x. | Double | Double |
sin(x) | Return the sine of angle. | Double | Double |
tan(x) | Return the tangent of angle | Double | Double |
cos(x) | Return the cosine of angle. | Double | Double |
Function prototype
A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type.
It doesn't contain function body.
A function prototype gives information to the compiler that the function
may later be used in the program.
Syntax of function prototype
The general structure of function prototype is
returnType functionName(type1 argument1, type2 argument2, ...);
Components of function prototype
It has three main components.
The data type of the function is the type of the returned value.
It does not return a value, the type is defined as void.
2. Name of the function:
The name of the function is any legal identifier followed by the
Parentheses without any spaces in between.
3. Arguments:
The arguments come inside the parenthesis, preceded by their
Types and separated by commas. If the function does not use any
Arguments, the word void is used inside the parenthesis
The Function prototype serves the following purposes –��1) It tells the return type of the data that the function will return.�2) It tells the number of arguments passed to the function.�3) It tells the data types of the each of the passed arguments.�4) Also it tells the order in which the arguments are passed to
the function.
Therefore essentially, function prototype specifies the input/output
interlace to the function i.e. what to give to the function and what to
expect from the function.
Prototype of a function is also called signature of the function.
Calling a function
Control of the program is transferred to the user-defined function
by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
In the above example, the function call is made using
addNumbers(n1, n2); statement inside the main() function.
Function definition
Function definition contains the block of code to perform a
specific task. In our example, adding two numbers and returning it.
Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...)
{ //body of the function }
When a function is called, the control of the program is
transferred to the function definition. And, the compiler starts
executing the codes inside the body of a function.
type function_name ( parameter type list )
{
declarations
statements
}
Some Terminology
Header: Everything before the first brace.
Body: Everything between the braces.
Type: Type of the value returned by the function.
Parameter List: A list of identifiers that provide information
for use within the body of the function.
Also called formal parameters.
#include <iostream>
using namespace std;
void prn_message(void); /* function prototype */
int main()
{
prn_message(); /* function invocation */
return 0;
}
void prn_message(void) /* function definition */
{
cout<<“A message for you”<<endl;
cout<<“Have a nice day!”;
}
Form of functions
Functions with or without arguments.
Functions can be used in four variations.
1- Functions that does not need any argument and also return no
value.
EXAMPLE:
void display (void);
void is used if:
A function takes no arguments.
If no value is returned by the function.
Form of functions
Functions with or without arguments.
Functions can be used in four variations.
2- Functions that need any argument and but does not return a
value.
EXAMPLE:
The parameter list is typically a comma-separated list of types.
void f(char c, int i);
void minimun (int a, int b);
void sqrt(double);
*In function prototype identifier is optional
If there is no return statement
#include <stdio.h>
using namespace std;
void prn_message();
void table(int num);
int main()
{
int num;
prn_message();
cout<<“\nEnter the table No:-”;
cin>>num;
table(num);
}
void prn_message()
{
cout<<“Program to print the table of a number\n”;
}
void table(int num)
{
for(int count=1; count <=10; count++)
cout<<num<<“ x ”<<count<<“ = ”<<num*count;
}
Code examples of functions with and without argument/parameter
3-Functions that does not need any argument and but return a
value.
EXAMPLE:
int minimun (void);
*When a return statement is executed, program control is immediately passed back to the calling environment.
4-Functions that need any argument and but also return a
value.
EXAMPLE:
double fact(int num);
Form of functions
Functions with return type
#include <iostream>
using namespace std;
double factorial (int num);
int main(void)
{
int num; double fact;
cout<<“Enter the number to find the factorial \n”;
cin>>num;
if(num>=0)
{
fact=factorial(num);
cout<<“Factorial of a “<<num <<“ is ”<<fact;
}
else
{
cout<<“Cannot find factorial for negative num”;
}
}
double factorial(int num)
{
double f=1;
for(int count=1; count<=num; count++)
f=f*count;
return f;
}
When the program flow reaches a return statement or the end of a function code block, it branches back to the function that called it.
If the function is any type other than void, the return statement will also cause the function to return a value to the function that called it.
Syntax: return [expression]
Return Statement
If expression is supplied, the value of the expression will be the return value.
If the type of this value does not correspond to the function type, the function type is converted, where possible. However, functions should always be written with the return value matching the function type
Return Statement
#include <stdio.h>
#include <stdlib.h>
list of function prototypes
int main(void)
{
. . .
}
int max(int a, int b)
{
. . .
}
int min(int a, int b)
{
. . .
}
void prn_random_numbers(int k)
{
. . .
}
Standard Style for Function Definition Order
#include <stdio.h>
#include <stdlib.h>
int max(int a, int b)
{
. . .
}
int min(int a, int b)
{
. . .
}
void prn_random_numbers(int k)
{
. . .
}
int main(void)
{
. . .
}
“Alternate Style for Function Definition Order
We will use the
standard style.
Using a Function
to Calculate the Minimum of 2 Values
#include <iostream>
using namespace std;
int min(int a, int b);
int main(void)
{
int j, k, m;
cout<<“Input two integers: ”;
cin>>j<<k;
m = min(j, k);
cout<<“Of two values ”<<j<<“ and ”<<k<<endl;
cout<<“The minimum is: “<<m;
return 0;
}
int min(int a, int b)
{
if (a < b)
return a;
else
return b;
}
ASSIGNMENT
Write a program using switch case to show three options.
1. Program to print multiplication table using function.
2. Program to find the largest number between three numbers using
functions
3. Program to find minimum between two numbers.
return expr;
or
exit(expr);
will return an integer value to the operating system.
Defining Default Arguments
The default values of a function’s arguments must be known when the function is called.
In other words, you need to supply them when you declare the function.
Example:
void moveTo( int x = 0, int y = 0);
Parameter names can be omitted, as usual.
Example:
void moveTo( int = 0, int = 0);
The function moveTo() can then be called with or without one or two arguments.
Example: moveTo (); moveTo (24); moveTo(24, 50);
#include <iostream>
using namespace std;
int sum(int x, int y, int z = 0, int w = 0)
{
return (x + y + z + w);
}
int sum(int x, int y, float z = 0, float w = 0)
{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Rules for defining default arguments
■ the default arguments are defined in the function prototype. They can also be supplied when the function is defined, if the definition occurs in the same source file and before the function is called
■ if you define a default argument for a parameter, all following parameters must have default arguments
■ default arguments must not be redefined within the prototype scope (the next chapter gives more details on this topic).
Possible Calls
When calling a function with default arguments you should pay attention to the following points:
■ you must first supply any arguments that do not have default values
■ you can supply arguments to replace the defaults
■ if you omit an argument, you must also omit any following arguments.
C++ Storage Class
Every variable in C++ has two features:
type and storage class.
Type specifies the type of data that can be stored in a variable. For example: int, float, char etc.
And, storage class controls two different properties of a variable: lifetime (determines how long a variable can exist) and scope (determines which part of the program can access it).
C++ Storage Class
A local variable is not created until the function in which it is defined is called.
(More accurately, we can say that variables defined within any block of code are not created until the block is executed.
Thus variables defined within a loop body only exist while the loop is executing.)
Scope
A variable’s scope, also called visibility, describes the locations within a program from which it can be accessed.
It can be referred to in statements in some parts of the program; but in others, attempts to access it lead to an unknown variable error message.
The scope of a variable is that part of the program where the variable is visible.
C++ Storage Class
Depending upon the storage class of a variable, it can be divided into different types:
Local variable
Global variable
Static local variable
C++ Storage Class
1-Local Variable
A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
C++ Storage Class: Local Variable Example
#include <iostream>
using namespace std;
void test();
int main()
{
// local variable to main()
int var = 5;
test();
// illegal: var1 not declared inside main()
var1 = 9;
}
void test()
{
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var;
}
C++ Storage Class
2- Global Variable
If a variable is defined outside all functions, then it is called a global variable.
The scope of a global variable is the whole program. This means, It can be used and changed at any part of the program after its declaration.
Likewise, its life ends only when the program ends.
C++ Storage Class: Global Variable Example
#include <iostream>
using namespace std;
// Global variable declaration
int c = 12;
void test();
int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
C++ Storage Class
3-Static Local variable
A static local variable exists only inside a function where it is declared (similar to a local variable) but its lifetime starts when the function is called and ends only when the program ends.
The main difference between local variable and static variable is that, the value of static variable persists the end of the program.
C++ Storage Class
3-Static Local variable
A static local variable has the visibility of an automatic local variable (that is, inside the function containing it).
However, its lifetime is the same as that of a global variable, except that it doesn’t come into existence until the first call to the function containing it.
C++ Storage Class: Static Variable Example
#include <iostream>
using namespace std;
void test()
{
// var is a static variable
static int var = 0;
++var;
cout << var << endl;
}
int main()
{
test();
test();
return 0;
}
[Not in SLO]
Heap and stack memory
What is a Stack?
A stack is a special area of computer’s memory which stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime.
It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased.
What is Heap?
The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation.
The heap is not managed automatically for you and is not as tightly managed by the CPU.
C++ Storage Class
Global and Local Functions in C++
The term local and global functions specify the scope of functions within programs, Based on the scope of functions, functions are categorized into two types; Local and global functions.
Local Functions:
Those functions which are defined inside the body of another function are called local functions. Normally, we use built-in function inside the body of main() function to perform our activities. Such declarations are termed as local.
Global and Local Functions in C++
//local functions
#include <iostream>
#include <stdlib.h>
int main()
{
int n;
cin>>n;
cout<<“absolute value of ”<<n<<“ = ”<<abs(n);
system("CLS");
return 0;
}
Global and Local Functions in C++
Global Functions:
A function declared outside any function is called global function. A global function can be accessed from any part of the program. Normally, user-defined functions are considered as global function because, usually they are defined before the main() function and are thus accessible to every part of the program.
Global and Local Functions in C++
Global functions are introduced as C++ functions defined at global or namespace scope which can be redefined later similar to virtual member functions.
C++ provides both global functions (defined at global or namespace scope, i. e., outside any class) and member functions belonging to a particular class
Another concept..
[Not IN SLO]
Inline Functions
Using function calls in programs, a lot of CPU time is wasted in passing control from the calling program (main() function) to the called function and returning control back to the calling program.
This limitation can be overcome by the use of inline functions.
In Inline functions, the functions return type is preceded by the inline keyword which request the compiler to treat function as inline and do not jump again and again to the calling function.
Inline Functions
General form of inline function.
inline int max( int x, int y)
{
return (x >= y ? x : y );
}
Why Inline Functions?
In the case of inline functions, when compiler compiles the code, all inline functions are expanded in-place, that is, function call is replaced with a copy of the contents of the functions itself, which removes the function call overhead
Why Inline Functions?
To save execution time in short functions, you may elect to put the code in the function body directly inline with the code in the calling program.
Long sections of repeated code are generally better off as normal functions:
The savings in memory space is worth the comparatively small sacrifice in execution speed.
But making a short section of code into an ordinary function may result in little savings in memory space, while imposing just as much time penalty as a larger function.
Why Inline Functions?
In fact, if a function is very short, the instructions necessary to call it may take up as much space as the instructions within the function body, so that there is not only a time penalty but a space penalty as well.
Calling an inline function is simple and is just like the calling to any other function.
Inline Functions?
#include <iostream>
using namespace std;
// lbsTokg() converts pounds to kilograms
inline float lbsTokg(float pounds)
{
return 0.453592 * pounds;
}
//--------------------------------------------------------------
int main()
{
float lbs; cout << “\nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbsTokg(lbs) << endl; return 0;
}
Call By Value
Demonstration Program for Call-by-Value
#include <iostream>
using namespace std;
int compute_sum(int n);
int main()
{
int n = 3, Sum;
cout<<n<<endl; /* 3 is printed */
Sum = compute_sum(n);
cout<<n <<endl; /* 3 is printed */
cout<<Sum <<endl;
return 0;
}
int compute_sum(int n)
{
int sum = 0;
for (; n > 0; --n) /* in main(), n is unchanged */
sum += n;
cout<<n<<endl; /* 0 is printed */
return sum;
}
Call By Reference
While calling a function, instead of passing the values of variables,
we pass address of variables(location of variables) to the function
known as “Call By References.
#include <stdio.h>
using namespace std;
void swapx(int*, int *);
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
cout<<“a = ”<<a<<“ and b = ”<<b;
return 0;
}
// Function to swap two variables by references
void swapx(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
cout<<“x = ”<<x<<“ and y = ”<<y;
}
Demonstration Program for Call-by-Reference
Function overloading
Functions in traditional programming languages, such as C, which perform the same task but have different arguments, must have different names.
To define a function that calculated the maximum value of two integers and two floating-point numbers, you would need to program two functions with different names.
Example:
int int_max( int x, int y);
double dbl_max( double x, double y);
Function overloading
C++ allows you to overload functions, that is, different functions can have the same name.
Example:
int max( int x, int y);
double max( double x, double y);
In our example two different function share the same name, max.
The function max() was overloaded for int and double types.
The compiler uses a function’s signature to differentiate between overloaded functions.
Advantages of using function overloading
Using function overloading, we can declare multiple functions with same name that have slightly different pruposes.
Function overloading can significantly lower complexity of programs.
As multiple functions have same name, therefore, remembering them is easier.
It exhibits the behavior of polymorphism(OOP concept)
Use of function overloading
Following are the features that disambiguate them and make them unique in a single program.
■ Number of arguments
■ Data types of arguments
■ Return type
Use of function overloading
Following are the features that disambiguate them and make them unique in a single program.
■ Number of arguments
Functions can be overloaded if they have different numbers of parameters. More than one function can have same name but different arguments.
Example:
int addition(int a, int b);
int addition(int a, int b, int c);
#include <iostream>
using namespace std;
int add(int a,int b);
int add(int a,int b, int c);
int main()
{
int x=6,y=7, i=9, j=10,k=17;
cout<<"\nAns of two parameters: "<<add(x,y);
cout<<"\nAns of three parameters: "<<add(i,j,k);
}
int add(int a,int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
Use of function overloading
Following are the features that disambiguate them and make them unique in a single program.
■ Data types of arguments
Example:
int divide(int a, int b);
double divide(float a, float b);
#include <iostream>
using namespace std;
int add(int a,int b);
double add(double a,double b);
int main()
{
int x=6,y=7,ans;
cout<<"\nAns of two parameters: "<<add(x,y);
double i=9.1,j=10.3;
cout<<"\nAns of three parameters: "<<add(i,j);
}
int add(int a,int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;
}
Use of function overloading
Following are the features that disambiguate them and make them unique in a single program.
■ Return type
The return type of a function is not considered when functions are overloaded. It means that if two or more functions with the same name have same function signatures but different return types then they are not considered as overloaded and compiler will generate error.
Example:
int display();
double display(); // this prototype generate error.
#include <iostream>
using namespace std;
int add(int a,int b);
double add(int a,int b); // illegal declaration: ambiguating declaration
int main()
{
int x=6,y=7,ans;
cout<<"\nAns of two parameters: "<<add(x,y);
int i=9,j=10;
cout<<"\nAns of three parameters: "<<add(i,j);
}
int add(int a,int b)
{
return a+b;
}
double add(int a,int b)
{
double ans=a+b;
return ans;
}
Recursion
A function that calls itself is said to be recursive. This process can also be performed indirectly if the function first calls another function or multiple functions before it is called once more. But a break criterion is always necessary to avoid having the function call itself infinitely.
Recursion
#include <iostream>
using namespace std;
void getput(void);
int main()
{
cout << "Please enter a line of text:\n";
getput();
cout << "\nBye bye!" << endl;
return 0;
}
void getput()
{
char c;
if( cin.get(c) && c != '\n')
getput();
cout.put(c);
}
Recursion