0% found this document useful (0 votes)
14 views

Functions

The document discusses functions and how they can be used to define new commands. It explains how functions are defined, how they execute, and how the main program calls functions. It also covers concepts like recursion, pointers, references, and passing arguments by value versus reference.

Uploaded by

GAMES TECH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Functions

The document discusses functions and how they can be used to define new commands. It explains how functions are defined, how they execute, and how the main program calls functions. It also covers concepts like recursion, pointers, references, and passing arguments by value versus reference.

Uploaded by

GAMES TECH
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Functions

Can we define a new command?


• Existing:
Sqrt(x) evaluates the square root of x
• Can we define new command?
Eg: gcd(m,n) should evaluate to GCD of m, n.

Function: official name for command


Example
• Write a program that print GCD of 36,24 and of 99, 47
• The already executed program can written twice to find the
gcd
int m=36, n=24;
while(m%n!=0)
{
Int r=m%n;
m=n;
n=r;
}
cout<<n<<endl;
Using a function
Int gcd(int m, int n)
{
while(m%n!=0){
int r= m%n;
m=n;
n=r;
}
return n;
}

Main-program{
Int a=36, b=24;
Cout<<gcd(a,b);
Cout<<gcd(99,47);
}
Using a function
• Code has two parts: Function definition + main program
• Main program
• “calls” or “invokes” function
o gcd(a,b)- call or invocation
o gcd(99,47)-another call
• Call includes values whose gcd is to be calculated
o a,b in first call
o 99,47 in second call
• Value supplied as part of call: “arguments to the call”
General form of function definition
Return-type name-of-function(parameter1-type parameter1-
name, parameter2-type parameter2-name, ..){
Function body
}
return type: the type of value returned by the function. Eg:int
• Some functions may not return anything
• Name-of-the-function: gcd
• Parameter: variables that will be used to hold the values of
the arguments to the functions. m,n in gcd.
• Function body: code that gets executed
How a function executes
• Main program execution begins
• When control reaches the function execution of main program is suspended not
stopped
• Preparation to run sub program (function) gcd
• Area allocated in where gcd will have its variables. “activation frame”
• Variables corresponding to parameters are created in activation frame
• Values of arguments are copied from activation frame of main program to gcd. This is
termed passing “arguments by value”
• Execution of gcd starts
• Execution of gcd is familiar (discussed earlier)
• Execution of function ends when return statement is encountered.
• Value following the return is copied back to the main program where function is called.
• Here it will be used in the place of expression gcd(...,....)
• Activation frame of function is destroyed. Memory reserved for it is taken back.
• Main program resumes and prints the output
Example
int gcd (int m, int n)
{....
return n}
int lcm(int m, int n)
{return m*n/gcd(m,n);
}
main-program{
cout<<lcm(50,75);
}
Execution
• Main program starts executing
• Call lcm reached. Main program suspends.
• Activation frame created for lcm.
• 50,75 copied to lcm.lcm starts execution.
• Call to gcd encountered.lcm suspends.
• Activation frame created for gcd.
• 50,75 copied to m,n.
o Execution of gcd starts
o Gcd computes 25 as result
o Result copied to activation frame of lcm
• Activation frame of gcd destroyed
• Lcm continues execution using result
• M*n/gcd(m,n) =50*75/25 =150 computed
• Returned to main-program
• Activation frame of lcmdestroyed
Points to remember
• Function: piece of code which takes the responsibility of
getting something done.
• Specification: what the function is supposed to do
“If the argument satisfies certain properties, then a certain
value will be returned or a certain action will happen”
• Certain properties=pre conditions
• Exmple: gcd: if positive integers are given as arguments,
then their GCD will be returned.
• If preconditions are not satisfied, there will be wrong
execution
Some shortcomings
• By using passing by values it is not possible to
do the following:
• A function that exchange the value of two
variables.
• A function that produce several values as
result:
o Function to produce polar coordinates given
cartesian coordinates.
Exchanging the value between two variables

void exchange(int m, int n)


{
int temp=m;
m=n;
n=temp;
return;
}
main-program{
int a=1,b=2;
exchange (a,b);
cout<<a<<b}
Execution
• Does not work. 1,2 will get printed
• When exchange is called 1, 2 are placed into
m,n.
• Execution of exchange exchanges value of
m,n.
• Change in m, n does not affect the values of
a,b of main program
Reference parameter
void exchange(int &m, int &n)
{
int temp=m;
m=n;
n=temp;
return;
}
main-program{
int a=1,b=2;
exchange (a,b);
cout<<a<<b}
Contd..
• &- before the name of the parameter
• Do not allocate space for this parameter, but
just instead use the variable from the calling
program.
• Now, when function changes m, n it is really
changing a, b.
• Such parameters are called reference
parameter
Remark
• If a certain parameter is a reference
parameter, then the corresponding argument
is said to be “passed by reference”
Cartesian to polar
void ctop (double x, double y, double &r, double &theta)
{
r=sqrt(x*x+y*y);
theta=atan2(y, x); //arc tan
return;
}
main program{
double x=1, y=1, r, theta;
ctop(x,y,r,theta);
cout<<r<<‘’<<theta <<endl;
}
Exercise
Write a program which takes a length in inches
and returns the length in yards, feet and
inches. Note that 12 inches make a foot and 3
feet make a yard. As an example: 100 inches =
3 yards, 2 feet, 4 inches.
Pointers
• If the memory of a computer has N bytes,
then the bytes are numbered 0....N-1.
• The number of a byte (different from what is
stored in the byte) is said to be its address.
• A pointer is a variable that can store address
• Things that can be accomplished using
reference variable can be accomplished using
pointers.
How to find the address of a variable
• The operator & can be used to get the address
of the variable.
• Ex: int t;
Cout<< &t<<endl;
• This prints the address of the variable ‘t’.
• Customarily, addresses get printed in
hexadecimal radix i.e.they will consist of a
sequence of hexadecimal digits prefixed by
“0x”.
Variables that can store addresses
• How to create a variable for storing addresses of variable of
type int.
• Int *v; // read as int star v
• The * is not to be read as multiplication.
• (int*) v; where int* means the type “address of int”.
• int p;
v=&p;
• Since p is of type int, &p has type address of int.
• Thus, it is ok to store &p in v, which is also of type address of int.
• Cout<<v<<‘ ’<<&p<<endl; //both print the same
• V=p; compile time error : type mismatch
Pointers in general
• In general to create a variable ‘w’ to store addresses of
variable of type T, write:
T* w;
• Assignment statement: types of lhs and rhs must be same
o Except when both sides are numeric types: then conversion
rules used.//we can take a float or double and store it in
‘int’ or vice versa.
o No conversion rule between pointers of one type and
pointers of other types.
o No conversion rule between pointers of one type and
values of any type.
The dereferencing operator*
• If ‘v’ contains the address of p, then we get to p by writing *v.
• Int *v;
Int p;
V=&p;
*v=10;//as good as p=10
• Think of * as the inverse of &
• &p: the address of the variable p
• *v:the variable whose address is in v
• Int *v;
v is such that *v is an int
V is an address of an int
Pointers in functions
Void ctop(double x, double y, double *pr, double *ptheta)
{*pr=sqrt(x*x +y*y);
*ptheta=atan2(x,y);
Return;
}
Main-program{
Double r,theta;
Ctop(1,1,&r,&theta);
cout<<r<<‘ ‘<<theta<<endl;
}
Contd..
• Main-program calls ctop, supplying &r, &theta as
third and fourth arguments.
• This is acceptable because corresponding
parameters have type double*.
• The first step of the call copies the address of r,
theta of the main-program into pr, ptheta of ctop.
• *pr means the variable whose address is in pr, in
other words, the variable r of main-program.
• Thus ctop changes the variables of main-program.
Contd...
• In variable definitions, * associates to the right. Example: int
*v, p;
• This means int *v; and int p; i.e. Defines a variable v of type
int* and variable p of type int.
• Assume that the only operation you can perform on a
variable of type T*are
• Dereference it
• Store into it a value &v where v is of type T
• Store it into another variable of type T*
• Pass it to a function as an argument, provided
corresponding parameter is of type T*.
Exercise
• Print out the errors in the code
Int *p, *q,w;
P=w;
Q=3;
• What is the result of executing the following:
Int *p,*q, w,x;
P=&w;
W=10;
Q=&x;
*q=20;
Cout<<*p+x<<endl;
Recursion
• Many physical and abstract object have the following
property
o The object has parts which are similar to the objects itself
o Such an object is said to be recursive or possess recursive
structure.
• Computation may also possess recursive structure
o While computing the GCD of m,n we find the GCd of n,m
%n.
o So it might seem that a function that finds GCD of m,n
should call itself with arguments n, m%n.
o Recursive functions
Euclid’s theorem on GCD
• Theorem: if m%n==0, then GCD(m,n)=n, else
GCD(m,n)=GCD(n,m%n)
• The theorem looks like a program!
Int gcd(int m, int n)
{if(m%n==0) return n;
Else return gcd(n, m%n)}
Execution
Int gcd(int m, int n)
{ if(m%n==0) return n;
Else return gcd(n,m%n)
}
Main-program
{cout<<gcd(205,103)<<endl;
}
Recursion
• Recursion= The phenomenon of a function calling itself
o Seems like we are defining the function in terms of itself
o But no circularity, if the arguments to the new call are
different from the arguments in the original call
• Each call executes in its own activation frame
• Some call must return without another recursive call
o Otherwise infinite recursion (error!)
• In the body of gcd there was just one recursive call. We
can several calls if we wish.
Comparison of recursive and non-recursive
gcd
Recursive calls in gcd(205, 123);
Gcd(123,82)
Gcd(82,41)
Non-recursive gcd
Values of m,n in consecutive iterations of gcd(205,123)
• 205,123
• 123,82
• 82,41
The two programs are really doing the same calculations!
Remarks
• Recursion often produces compact, elegant
programs
o Recursive programs might be slightly slower because
they need to create activation frame.
• Recursion is also a way to discover algorithms
o Euclid quite possibly thought to himself, ”Instead of
doing laborious computation to find the gcd of 205
and 123, can i find two smaller numbers whose gcd
is same as that of 205 and 123?”
o This is recursive thinking
Inline functions
• When a function is defined “inline”, the
compiler copies the code of the function in
the calling function.
• Passing of control between caller and callee
function is avoided.
• Inline functions are used for small functions
• Inline function increases the speed but
requires more memory
Assignment 1
• Illustrate some situation where inline
functions may not work
How do we write large programs
• Designing / building anything large becomes easier
if we can think of it as made of small parts.
• Example:
o A book is made of chapters
o A car is made of many subsystem
• For program, smaller part = functions
o We break up the overall requirements into separate,
small, somewhat independent computations
o Code up the separate part as separate functions
Why dividing code into function helps
• Different people write different functions, so
work can be divided
• Functions are self documenting
o Function name, parameters give clue as to
what it does
o Eg: int gcd(int m, int n)
• Write a little bit of code, test it, write some
more(each function can be tested individually)
Contd..
• Maximum size of any function < 20 lines
• We use functions written by others when
programming
• Eg:Library functions
Splitting a program into many files
• A program may contain several functions.
o All need to be placed in the same file
• If code in a file F calls a function f:
o Function f must be declared inside F, textually any
call before it.
• A function definition is a declaration
o But there can be other ways to declare it
• Every function must be defined in just one of the
files that are used for a program.
Function declaration
• A function declaration is essentially the definition without the body.
• Example: Declaration of gcd function: int gcd (int m, int n)
• Also acceptable: int gcd(int, int)
• The declaration tells the compiler that if the name gcd appears later, it
will be a function and take 2 arguments of the specified type.
• Compiler can now check if the name is used correctly in the rest of the
file.
• If a file contains call to function but does not contain its definition:
• It can only be partially compiled into an object module
• To get an executable program, all the object module containing all
called functions must be linked together.
• Other names for declaration: Signature, Prototype
Header files
• Tedious too remember what declaration to include in each file
• Instead we put all declaration into a header file and “include ”
the header file into every file
• Header file gcdlcm.h
Int gcd(int, int);
Int lcm(int, int);
• The directive “# include filename”
o Gets replaced by the content of the file name
o It is acceptable if we declare functions that do not get used
o It is acceptable if we have both a declaration and then the
definition of a function in the same file.
Example
• File gcd.cpp
#include “gcd.h”
Int gcd(int m, int n)
{...}
• File lcm.cpp
#include “gcdlcm.h”
Int lcm(int m, int n)
{....}
• File main.cpp
#include<iostream>
#include “gcdlcm.h”
Int main()
{......}
More on header files
• Header files customarily have the suffix .h
or .hpp or no suffix
• If header file is mentioned in “”, it is picked up
from the current directory
• If it is mentioned in <>, it is picked up from
some standard place, eg, iostream
Name spaces
• Suppose many people cooperatively develop a single
program.
• Possible several may define function with the same
name.
• Creates conflict / ambiguity
• Can be avoided using name spaces
• Namespaces=catalog of names
• Full name of function f defined in namespace N is N::f
• Suppose f is defined in two namespaces N and P, we
can specify which we mean by writing N::f or P::f
Defining a namespace
• Namespace N{
Declarations/definitions of name}
• This creates a namespace with name N and
also defines / declares names inside it.
• A name g defined without putting it inside a
namespace is said to belong to the global
namespace. It’s full name is ::g
Example
• Namespace N{
Int gcd(int m, int n) {....}
Int lcm(int m, int n) {....}
}
Using Namespace P;
{
Int gcd(int m, int n) {....}
Int lc(int m, int n) {....}
}

Int main(){
Cout<<N::lcm(36,24)<<lc(36,24)endl;
Cout<<N::lcm(2,4)
}
The using directive
• Suppose you refer to names defined in some
namespace N frequently
• You may find it tedious to write N:: all the time
• Put the following line at the top of your
pragram
o Using namespace N;
• Then you will be allowed to use any name
from N without having to write N:: before it.
Example using “using”
• Namespace N{
Int gcd(int m, int n){....}
Int lcm (int m , int n){...}
}
Using namespace N;
Int main(){
Cout<<lcm(36,24)<<endl;
}
Scope resolution operator
• The scope resolution operator ( :: ) is used for several reasons. For example: If the
global variable name is same as local variable name, the scope resolution operator
will be used to call the global variable.
Example:
#include <iostream>
using namespace std;
char a = 'm';
static int b = 50;
int main()
{
char a = 's'; cout << "The static variable : "<< ::b;
cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a;
return 0;
}
simplecpp
• # include <simplecpp> includes the following
lines
• # include <iosream>
• #include<cmath>
• Using namespace std;
o These lines are useful . The names cout, cin, endl
are defined in the namespace std, in the
standard header file iostream.
• Using simplecpp, we will be able to do graphics

You might also like