Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 1
UNIT-III: Subprograms and Blocks: Fundamentals of sub-programs, Scope and lifetime of variable,
static and dynamic scope, Design issues of subprograms and operations, local referencing
environments, parameter passing methods, overloaded sub-programs, generic sub-programs, design
issues for functions overloaded operators, co routines.
General Subprogram Characteristics
Each subprogram has a single-entry point
The calling program is suspended during execution of the called
subprogram
Control always returns to the caller when the called subprogram’s
execution terminates
Basic Definition
A subprogram definition describes the interface to and the actions of the
subprogram abstraction
A subprogram call is an explicit request that the subprogram be executed
A subprogram header is the first part of the definition, including the
name, the kind of subprogram, and the formal parameters
The parameter profile of a subprogram is the number, order, and types of
its parameters
There are two distinct categories of subprograms, procedures and
functions.
Procedures: provide user-defined parameterized computation
statements.
Functions: provide user-defined operators which are semantically
modeled on mathematical functions.
The protocol is a subprogram’s parameter profile and, if it is a function,
its return type.
Function declarations in C and C++ are often called prototypes
A subprogram declaration provides the protocol, but not the body, of the
subprogram.
Parameter: A formal parameter is a dummy variable listed in the
subprogram header and used in the subprogram
Argument: An actual parameter represents a value or address used in the
subprogram call statement.
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 2
Design Issues for Subprograms
1. What parameter passing methods are provided?
2. Are parameter types checked?
3. Are local variables static or dynamic?
4. Can subprogram definitions appear in other subprogram definitions?
5. What is the referencing environment of a passed subprogram?
6. Can subprograms be overloaded?
7. Are subprograms allowed to be generic?
Argument/Parameter Correspondence
Positional
The binding of actual parameters (arguments) to formal parameters is by
position: the first actual parameter is bound to the first formal parameter
and so forth
Safe and Effective
Keyword
The name of the formal parameter to which an actual parameter
(argument) is to be bound is specified with the actual parameter
Advantage: Parameters can appear in any order, thereby avoiding
parameter correspondence errors
Disadvantage: User must know the formal parameter’s names
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 3
Call by value in Java
class Main {
public static void main ( String[] args ) {
int x =3, y=4;
System.out.println ( "Value of x before calling is "+x+" "+y);
swap(x,y);
System.out.println ( "Value of x after calling is "+x+" "+y);
}
public static void swap ( int a, int b ) {
int t;
t = a;
a = b;
b = t;
}
}
Call By Reference
class Number {
int x,y;
}
class Main {
public static void main ( String[] args ) {
Number a = new Number();
a.x=3;
a.y=4;
System.out.println("Value of a.x and a.y before calling is "+a.x+" "+ a.y);
swap(a);
System.out.println("Value of a.x and a.y after calling is "+a.x+" "+ a.y);
}
public static void swap(Number n) {
int t;
t=n.x;
n.x = n.y;
n.y = t;
}
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 4
Swap in C++ Call by value
#include<iostream>
using namespace std;
void swap(int a, int b)
{
int t;
t = a; a = b; b = t;
}
int main()
{
int a=3,b=4;
cout<<a<<" "<<b<<endl;
swap(a,b);
cout<<a<<" "<<b<<endl;
}
Swap in C++ Call by reference: pointer
#include<iostream>
using namespace std;
void swap(int *a, int *b)
{
int t;
t = *a; *a = *b; *b = t;
}
int main()
{
int a=3,b=4;
cout<<a<<" "<<b<<endl;
swap(&a,&b);
cout<<a<<" "<<b<<endl;
}
Swap in C++ Call by reference: Alias
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int t;
t = a; a = b; b = t;
}
int main()
{
int a=3,b=4;
cout<<a<<" "<<b<<endl;
swap(a,b);
cout<<a<<" "<<b<<endl;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 5
Parameter as an Array: In C++, we can pass an element of an array or the full
array as an argument to a function. However, a pointer is passed to an array
by specifying the array's name without an index. There are following three
ways to pass an array.
Way-1: Formal parameters as a pointer as follows −
void myFunction(int *param) {
.
}
Way-2: Formal parameters as a sized array as follows −
void myFunction(int param[10]) {
.
}
Way-3: Formal parameters as an unsized array as follows −
void myFunction(int param[]) {
.
}
#include <iostream>
using namespace std;
// function declaration:
void swapTwoValue(int arr[])
{ int temp; temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; }
int main () {
// an int array with 2 elements.
int val[] = {10,20};
cout<<"Before Swapping.."<<endl;
cout << "val[0]: " << val[0] << endl; cout << "val[1]: " << val[1] << endl;
// pass pointer to the array as an argument.
swapTwoValue(val) ;
// output the returned value
cout<<"After Swapping.."<< endl;
cout << "val[0]: " << val[0] << endl; cout << "val[1]: " << val[1] << endl;
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 6
For-each loop
There is a new form of for loop which makes iterating over arrays easier. It is
called for-each loop. It is used to iterate over an array. Let's see an example of
this.
#include <iostream>
using namespace std;
// function declaration:
int main()
{
int ar[] = { 1,2,3,4,5,6,7,8,9,10 };
for (int m : ar)
{
cout << m << endl;
}
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 7
Parameter As Structure
#include<iostream>
using namespace std;
struct Array1
{
int a;
int b;
}X = {1,2};
void swapStructVal(struct Array1 &Y)
{
int t;
t = Y.a;
Y.a = Y.b;
Y.b = t;
}
int main()
{
cout<<"before:"<<X.a<<" "<<X.b<<endl;
swapStructVal(X);
cout<<"After:"<<X.a<<" "<<X.b<<endl;
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 8
Returning Parameter from function
#include<iostream>
using namespace std;
struct Array1
{
int a;
int b;
}X = {1,2};
struct Array1 swapStructVal(struct Array1 Y)
{
int t;
t = Y.a;
Y.a = Y.b;
Y.b = t;
return Y;
}
int main()
{ //struct Array1 Z;
cout<<"before:"<<X.a<<" "<<X.b<<endl;
struct Array1 Z = swapStructVal(X);
cout<<"After:"<<Z.a<<" "<<Z.b<<endl;
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 9
Parameter As Object
How to pass objects to a function?
#include <iostream>
using namespace std;
class Num
{ private: int M;
public: Num(int Val) { M=Val; }
void Swap(Num &X)
{ int t; t = X.M ; X.M = M; M = t; }
void display() { cout << "M:"<<M<<endl; }
};
int main()
{
Num A(10),B(20);
cout<<"Before:"<<endl; A.display(); B.display();
B.Swap(A);
cout<<"After:"<<endl; A.display(); B.display();
return 0;
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 10
}
Parameter passing modes
In:
o Call by value and writes to the parameter are prohibited in the
subroutine
out:
o Call by result, which uses a local variable to which the writes are made
o The resulting value is copied to the actual parameter to pass the value
out when the subroutine returns
In/Out:
o Call by value/result uses a local variable that is initialized by assigning
the actual parameter's value to it
o The resulting value is copied to the actual parameter to pass the value
out when the subroutine returns
//In Mode
int foo(int n) { return n*n;}
//Out Mode
int foo2(int *n) { int m=500; *n=m*2; return *n+10; }
//In/Out Mode
int foo1(int *n) { int m; m = *n + 1; *n = m*2; return *n+10;}
int main()
{
cout<<foo(10)<<endl; //100
int a=10;
cout<<foo1(&a)<<" "<<a<<endl;
cout<<foo2(&a)<<" "<<a<<endl;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 11
Techniques used for argument passing in traditional imperative languages
call by value (in): copy going into the procedure. This is the mechanism used by
both C and Java. Note that this mechanism is used for passing objects, where a
reference to the objected is passed by value.
call by result (out): copy going out of the procedure, the formal parameters are
copied back into the actual parameters. (Note that this only makes sense if the actual
parameter is a variable, or has a l-value, such as an array element.)
call by value result (in+out): copy going in, and again going out
call by reference (in+out): The actual parameters and formal parameters are
identified. The natural mechanism for this is to pass a pointer to the actual parameter,
and indirect through the pointer
call by name (in+out): re-evaluate the actual parameter on every use. For actual
parameters that are simple variables, this is the same as call by reference.
Macros: Macros are piece of code in a program which is given some name.
Whenever this name is encountered by the compiler the compiler replaces the name
with the actual piece of code. The ‘#define’ directive is used to define a macro. Let
us now understand macro definition with the help of a program:
#include <iostream>
using namespace std;
#define MIN(a,b) (((a)<(b)) ? a : b)
int main ()
{
int X, Y;
X = 10;
Y = 20;
cout <<"The minimum is " << MIN(X,Y) << endl;
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 12
Inline Functions
Functions can also be defined, like macros. One primary difference between
inline and macro function is that the inline functions are expanded during
compilation, and the macros are expanded when the program is processed by
the preprocessor.
Advantages
The inline function reduces the overhead of function calling and returning
which in turn reduces the time of execution of the program. Also, the
arguments are pushed onto the stack and registers are saved when a function
is called and reset when the function return, which takes time, this is avoided
by the inline functions as there is no need of creating local variables and
formal parameters each time.
Inline functions can be a member of the class and can also access the data
member of the class.
Inline function reduces the time of execution of the program but, sometimes
if the length of the inline function is greater then, the size of the program will
also increase because of the duplicated code. Hence, it is a good practice to
inline very small functions.
The inline function’s argument is evaluated only once.
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
return 0;
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 13
Mutable Keyword
The mutable storage class specifier in C++ (or use of mutable keyword in C++)
auto, register, static and extern are the storage class specifiers in C. typedef is
also considered as a storage class specifier in C. C++ also supports all these
storage class specifiers. In addition to this C++, adds one important storage
class specifier whose name is mutable.
The data members of a constant object cannot be changed. If we want some
data members to change even when the object is constant, it can be using
mutable keyword. The following function shows the use of mutable keyword:
#include <iostream>
#include <string.h>
using std::cout;
using std::endl;
class mobile
{ char model[20]; mutable char owner[20]; int yrofmfg; char mobilereg[10];
public: mobile(char *m, char *o, int y, char *r)
{ strcpy(model, m); strcpy(owner, o); yrofmfg = y; strcpy(mobilereg, r); }
void changeowner(char *o) const
{ strcpy(owner, o); }
void display() const
{cout << model << endl << owner << endl << yrofmfg << endl << mobilereg;}
};
int main (int argc, char *argv[])
{
const mobile c1("E250", "Gupta", 2006, "KX091EXW342");
c1.display();
c1.changeowner("Ghosh");
c1.display();
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 14
Virtual Function
What is virtual function?
Virtual function is the member function of a class that can be overriden in its
derived class. It is declared with virtual keyword. Virtual function call is resolved
at run-time (dynamic binding) whereas the non-virtual member functions are
resolved at compile time (static binding).
Polymorphism is achieved in C++ using virtual functions. If a function with same
name exists in base as well as parent class, then the pointer to the base class
would call the functions associated only with the base class. However, if the
function is made virtual and the base pointer is initialized with the address of
the derived class, then the function in the child class would be called.
Virtual functions ensure that the correct function is called for an object,
regardless of the expression used to make the function call.
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 15
#include<iostream>
using namespace std;
class base
{
public:
virtual void print () { cout<< "print base class" <<endl; }
void show () { cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () { cout<< "print derived class" <<endl; }
void show () { cout<< "show derived class" <<endl; }
};
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
derived d1;
d1.print();
d1.show();
}
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 16
Virtual Class
a virtual class is a nested inner class whose functions and member variables can
be overridden and redefined by subclasses of an outer class.
Virtual base class is used in situation where a derived have multiple copies of
base class. Consider the following figure:
Example without using virtual base class
#include<iostream.h>
#include<conio.h>
class ClassA
{
public: int a;
};
class ClassB : virtual public ClassA
{
public: int b;
};
class ClassC : virtual public ClassA
{
public: int c;
};
class ClassD : public ClassB, public ClassC
{
public: int d;
};
Vivek Dubey
Vivek DubeySubject: Principle of Programming Language/eNotes:Unit-3
Computer Science & Engg Dept Page 17
void main()
{
ClassD obj;
obj.a = 10;
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
}
Output :
A : 10
B : 20
C : 30
D : 40