Chapter #4
Chapter #4
1
FUNCTIONS
Function is group of program statements that can
act on data and return a value.
Every C++ program has at least one function,
When your program starts, main () is called
automatically.
main ( ) might call other functions, some of
which might call still others.
2
The reason why we use functions is to aid
modularization of a program.
A function reduces program size.
Any fragments of code that are needed
frequently in a program are best
candidates to be written as a function.
3
Function Declaration / Prototype Declaration
4
Example
5
Function Definition
6
Example
Void getnumber()
{
int x;
cout<< “Enter Number \n”;
cin>>number;
cout<<”The number you enterd is:”<<number;
}
The function body is placed in one place in memory. But
it could be invoked in several places in the program.
7
Calling functions
8
// the following program demonstrates what we have discussed so far
#include<iostream>
Using namespace std;
void add ( );
void sub ( );
void main ()
{ char ch;
cout <<" what do you want ? A: Add, S: subtract \n";
cin>>ch;
switch(ch) {
case 'A': // A for addition
add ( ) ;
break;
case 'S' : // S for subtraction
sub ( );
break;
}} 9
void add()
{ int a,b,c;
cout<<"enter two numbers \n";
cin>> a>>b;
c = a + b;
cout <<" the sum is \t "<< c;
}
void sub ( )
{ int a,b,c;
cout<<"Enter two numbers \n";
cin>>a>>b;
cout<<"the difference is \t "<<a-b;
}
10
Parameters and Arguments
• C++ supports two styles of parameters: value and reference.
A value parameter receives a copy of the value of the argument passed to
it. As a result, if the function makes any changes to the parameter, this will
not affect the argument. For example, in the following simple program,
#include <iostream>
void Foo (int num);
int main (void)
{int x = 10;
Foo(x);
cout << "x = " << x << '\n';
return 0;}
void Foo (int num)
{num = 0;
cout << "num = " << num << '\n';
}
11
• the single parameter of Foo is a value parameter. As far
as this function is concerned, num behaves just like a
local variable inside the function.
• When the function is called and x passed to it, num
receives a copy of the value of x. As a result,
although num is set to 0 by the function, this does not
affect x.
The program produces the following output:
• num = 0;
• x = 10;
12
Reference parameter
A reference parameter, on the other hand, receives
the argument passed to it and works on it directly.
Any change made by the function to a reference
parameter is in effect directly applied to the
argument.
It is perfectly valid for a function to use pass-by-
value for some of its parameters and pass-by-
reference for others.
The former is used much more often in practice.
13
Example2
17
# include<iostream>
int year = 2021; // global variable
int Max (int, int); // global function
int main () // global function
{
int x,y;
cout<<"enter first number"<<endl;
cin>>x;
cout <<"enter the second number"<<endl;
cin>>y;
cout<<"year"<<year<<endl;
Max(x,y);
}
int Max(int x, int y)
{ if( x>y)
cout<<"the minimum is"y;
else if (y<x)
cout<<"the minimum is"x;
else
cout<<"they are equal";
cout<<"year"<<year<<endl;
} 18
• Un initialized global variables are automatically initialized to zero.
Since global entities are visible at the program level, they must also be unique
at the program level.
• This means that the same global variable or function may not be defined
more than once at the global level.
• Global entities are generally accessible everywhere in the program.
• Each block in a program defines a local scope. Thus the body of a function
represents a local scope.
• The parameters of a function have the same scope as the function body.
• Variables defined within a local scope are visible to that scope only. Hence,
a variable need only be unique within its own scope.
• Local scopes may be nested, in which case the inner scopes override the
outer scopes.
19
For example, in
int x,y,z ; // xyz is global
void Foo (int x, int y, int z) // xyz is local to the body of Foo
{
if (x> 0)
{
double x,y,z; // xyz is local to this block
//...
}}
20
Default Arguments
Default argument is a programming convenience which removes the
burden of having to specify argument values for all of a function’s
parameters.
For example, consider a function for reporting errors:
void Error (char message, int severity = 0);
• Here, severity has a default argument of 0; both the following calls are
therefore valid:
Error( ‘x’, 3); // severity set to 3
Error( ‘R’); // severity set to 0
As the first call illustrates, a default argument may be overridden by
explicitly specifying an argument.
Default arguments are suitable for situations where certain (or all) function
parameters frequently take the same values. In Error, for example, severity
0 errors are more common than others and therefore a good candidate for
default argument. A less appropriate use of default arguments would be:
int Power (int base, unsigned int exponent = 1);
21
• Because 1 (or any other value) is unlikely to be a frequently-used one in
this situation.
• A default argument need not necessarily be a constant. Arbitrary
expressions can be used, so long as the variables used in the expression
are available to the scope of the function definition (e.g., global
variables).
• The accepted convention for default arguments is to specify them in
function declarations, not function definitions.
• Because function declarations appear in header files, this enables the
user of a function to have control over the default arguments. Thus
different default arguments can be specified for different situations.
• It is, however, illegal to specify two different default arguments for the
same function in a file.
22
Example
# include<iostream.h>
int devide (int a, int b=2);
int main()
{
cout<<devide(12);// Here the default value 2 is passed as a second argument.
cout<<endl;
cout<<devide(20,4);
return 0;
}
int devide (int a, int b)
{
int r;
r=a/b;
return (r);
}
23
Variable Number of Arguments / Overloaded functions
Two different functions can have the same name if the prototype e of their arguments
are different. That means that you can give the same name to more than one function if
they have either a different number of arguments or different types in their arguments.
Example
# include<iostream.h>
int devide (int a, int b=2);
int devide(int z, int r, int y);
float devide (float a, float b);
int main()
{int x=20, y=2;
float n=5.0, m=2.0;
cout<<devide(x,y);
cout<<endl;
cout<<devide(n,m);
cout<<endl;
cout<<devide(n,m,m);
cout<<endl; 24
int devide (int a, int b)
{
return a/b;
}
int devide (int a, int b, int c)
{
int w=a/b
return w/c;
}
float devide (float x, float y)
{
return x/y;
}
25
• In this case we have defined two functions with the same name,
but one of them accept two arguments of type int and the other
accepts them of type float the compiler knows which one to call
in each case by examining the type when the function is called.
• If it is called with two ints as an argument it calls to the
function that has two int arguments in the prototype if it is called
with two floats it will call to the one which has two floats in its
prototype.
• For simplicity I have included the same code with both functions,
but this is not compulsory. You can make two functions with the
same name but with completely different behavior.
26
Recursion
27
int Factorial (unsigned int n)
{
return n == 0 ? 1 : n * Factorial(n-1);
}
For n set to 3, the table below provides a trace of the
calls to Factorial. The stack frames for these calls
appear sequentially on the runtime stack, one after
the other.
28