0% found this document useful (0 votes)
41 views18 pages

PPL IV Unit-1

The document discusses subprograms (also called subroutines, procedures, functions, and methods), which are sequences of instructions that can be invoked from other locations in a program and then return execution to the instruction following the call. Subprograms allow for code reuse and abstraction. They can have parameters, local variables, and return values. Languages use different mechanisms for parameter passing and managing local variables, which are either static or dynamically allocated on the runtime stack.

Uploaded by

Gvzgjbc Ccdbnmn
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)
41 views18 pages

PPL IV Unit-1

The document discusses subprograms (also called subroutines, procedures, functions, and methods), which are sequences of instructions that can be invoked from other locations in a program and then return execution to the instruction following the call. Subprograms allow for code reuse and abstraction. They can have parameters, local variables, and return values. Languages use different mechanisms for parameter passing and managing local variables, which are either static or dynamically allocated on the runtime stack.

Uploaded by

Gvzgjbc Ccdbnmn
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/ 18

UNIT IV

Subprograms
 A subprogram is a sequence of instructions whose execution is
invoked from one or more remote locations in a program, with the
expectation that when the subprogram execution is complete,
execution resumes at the instruction after the one that invoked the
subprogram.
 In high-level languages, subprograms are also called subroutines,
procedures, and functions.
 In object-oriented languages, they are usually called methods or
constructors.
 In most modern high-level languages, subprograms can have
parameters, local variables, and returned values.
 At the assembly language level, use of subprograms requires
subprogram linkage protocols.
 These protocols involve designating registers for special purposes
and the use of special instructions for subprogram calls and returns.

Basic concept:
 Two fundamental abstraction facilities can be included in a
programming language:
 Process abstraction
 Data abstraction.

In the early history of highlevelprogramming languages, only


process abstraction was included. Processabstraction, in the form
of subprograms, has been a central concept in allprogramming
languages

 In the 1980s, however, many people began to believe that


data abstraction was equally important.
 In a modern programming language, such a collection of
statements is written as a subprogram.
 This reuse results in several different kinds of savings,
primarily memory space and coding time.

General Subprogram Characteristics:

 Each subprogram has a single entry point

 The calling program unit is suspended during the execution of the


calledsubprogram, which implies that there is only one subprogram
in executionat any given time.

 Control always returns to the caller when the subprogram


executionterminates.

Basic Definitions:

A subprogram definition is a description of the actions of the subprogram


abstraction.
 A subprogram call is an explicit request that the called subprogram
be executed.
 A subprogram is said to be active if, after having been called, it has
begunexecution but has not yet completed that execution.
 The two fundamental types of the subprograms are:
 Procedures: it’s have not return value.
 Functions: it’s have return value.
 We cannot call procedure assign to variable while in function
can do.

Function procedure
int sum(int x, int y) void sum(int x, int y)
{ {
return x+y ;
} }

int sum(int x, int y)


{
return x+y;
}
void add(int x, int y)
{
int Z = sum(x+y);
printf (z);

}
Void main()
{
sum(2,3);
add(3,8);

int z = sum(3,5); //this is right


int y = add(3,2); //this is wrong
}

Need of subprogram :

1. Increase Readability
2. Reuse of code
3. Saving coding time
4. Abstraction achieved
A subprogram header is the first line of the definition, serves several
definitions:
 It specifies that the following syntactic unit is a subprogram
definition of someparticular kind.
 The header provides a name for the subprogram.
 May optionally specify a list of parameters.Consider the following
header examples:

 Fortran
Subroutine Adder(parameters)

 Ada
procedure Adder(parameters)

 C
void Adder(parameters)

 java
publicintaddNumbers(parameters)

 Python
defmyFun(parameters)

Parameters in the header are formalparameters, parameters in the


call are actual parameters

• Subprogram design issues:


– what mode(s) of parameter passing is used?
– should parameters be type checked?
– can a parameter be a subprogram name?
– are local variables static or stack dynamic (or other)?
• static variables do not permit recursion
– Is separate compilation of subprograms allowable?
– Can subprograms be generic or overloaded?
Three modes of parameter passing:
– in mode (parameters going from program to subprogram)

– out mode (parameters going from subprogram to program)

– in-out mode (both).

Mainfun subfunction

• Implementations:
– Pass by Value (in)
– Pass by Result (out)
– Pass by Value-Result (inout)
– Pass by Reference (inout)
– Pass by Name (varies)

Type Checking of Parameters


Type checking means checking that each operation should receive proper number of
arguments and of proper data type.

A=B*j+d;
* and+ are basically int and float data types based operations and if any

variable in this A=B*j+d;is of other than int and float then compiler will generate

type error.

1) Static Type Checking : checked at compile time

2) Dynamic Type Checking: Checked at run time

 F77,Perl, JavaScript, PHP and earlier: no type checking at all

 Pascal, Modula-2, F90, Ada, Java: type checking required

 C++: type checking required

Parameters that are Subprogram names

We want the subprogram to execute independently of the function, so


we write it so that the we pass function’s name that we want to integrate
to an integrate subprogram like enum, stuct, union.

double integrate(double *(f)(double x), double lowerbd, double upperbd)

{
double result, i;

result = f(i);
…}

Note: This is available in C/C++, Fortran 90/95 and JavaScript

In languages that allow nested subprograms, such as JavaScript, there is


another issue related to subprogram names that are passed as
parameters.

 The question is what referencing environment for executing the


passed subprogram should be used.
 The three choices are:
1. It is the environment of the call statement that enacts the passed
subprogram “Shallow binding.”
2. It is the environment of the definition of the passed subprogram
“Deep binding.”
3. It is the environment of the call statement that passed the
subprogram as anactual parameter ”Ad hoc binding; has never
been used”

Ex: “written in the syntax of Java


function sub1( ) {
varx;

function sub2( ) {
alert(x); // Creates a dialog box with the value of x
};
function sub3( ) {
varx;
x = 3;
sub4(sub2);
};
function sub4(subx ) {
varx;
x = 4;
subx( );
};
x = 1;
sub3( );
};

Local Referencing Environments: static and stack-dynamic variables

 Variables that are defined inside subprograms are called local vars.
 Local variables can be either static or stack dynamic “bound to
storage when the programbegins execution and are unbound when
execution terminates.”
Static variables
o Static variables are bound to their memory cells by the loader which
puts the program into RAM
o They remain bound to the same location until the program
terminates.
o The association of variable name and address is kept by the symbol
table.
o So this binding takes place before execution, and remains for the
entire time the program is executing.
o Static variables are very efficient, but have reduced flexibility.
o Languages that have only static variables cannot support recursion.
o They also do not allow storage to be shared.
o The lifetime of static variables is the duration of the execution of the
program.

 Static variables are variables which have a property of preserving their


values even when they go out of scope.
 They preserve their value from the previous scope and are not initialized
again.
 Static variable remains in memory throughout the span of the program.
 Static variables are initialized to 0 if not initialized explicitly.
 In C. static variables can only be initialized using constant literals.

intfun()
{
int x = 10; // stack dynamic
staticintcount = 5; //static
count++;
x++;
returnx++;
}
intmain()
{

printf("%d ", fun());//10 //5


printf("%d ", fun()); //11 //6
inti = fun();. //7
printf(" value of i = %d", i);
return0;
}
Stack-dynamic variables
 Stack-dynamic variables are usually local variables of functions. This
includes arguments to the functions.
 Stack-dynamic variables bindings are created when the declaration
statements are elaborated.
 Elaboration refers to the storage allocation and binding process which
takes place when the code is executed i.e. when the function is called.
 When a function is called, its local variables are allocated space on the
runtime stack, and the variable is bound to the address.
 When the function returns, all the space used by the function is de-
allocated.
 Note: that the space allocated is on the stack (static RAM), but that it is
allocated and de-allocated at runtime (dynamically).

public class Recur


{
publicint begin(int a)
{
if(a == 0)
return a;
else
return a + begin(--a);
}

public static void main(String [] args)


{
System.out.println(new Recur().begin(3));
}
}

Advantages of using stack dynamic:


a. Support for recursion.
b. Storage for locals is shared among some subprograms.

Disadvantages:
a. Allocation/deallocation time.
b. Indirect addressing “only determined during execution.”
c. Subprograms cannot be history sensitive “can’t retain data values
of local varsbetween calls.”
Advantages of using static vars:
a. Static local vars can be accessed faster because there is no
indirection.
b. No run-time overhead for allocation and deallocation.
c. Allow subprograms to be history sensitive.

Disadvantages:
a. Inability to support recursion.
b. Their storage can’t be shared with the local vars of other
inactivesubprograms.
c. In C functions, locals are stack-dynamic unless specifically
declared to be static.

Ex:
int adder(int list[ ], intlistlen)
{
staticint sum = 0; //sum is static variable
int count; //count is stack-dynamic
for (count = 0; count <listlen; count++)
sum += list[count];
return sum;
}

GENERIC SUBPROGRAMS

 A generic subprograms is a subprogram which have parametric


polymorphism.
 A generic subprogram can accept different types of values of same
single memory location.
 C++, JAVA, C#, ADA, provide a kind of compile-time parametric
polymorphism.
 Not required type checking.

For example Generic Functions in C++:


#include <iostream>
using namespace std;
template<class j>
void show(j a)
{
cout<<a;
}
int main()
{
show(10);
show(10.2);
show(‘c’);
show("hello this is generic program");
return 0;
}

Example in java:
classDemoClass {
public<T> void genericsMethod(T var1)
{
System.out.println("Generics Method:\n");
System.out.println("Data Passed: " + var1);
}}
class Main {
public static void main(String[] args) {
DemoClassdemo = new DemoClass();
demo.genericsMethod("Java Programming\n");
demo.genericsMethod(25);
}
}
Parameter Passing Method :

Formal parameters are characterized by one of three distinct


semantics models:
(1) They can receive data from the corresponding actual parameter;
(2) they can transmit data to the actual parameter; or
(3) they can do both.
These models arecalled in mode, out mode, and inout mode,
respectively.

Implementation Models of Parameter Passing:

Pass-by-Value:

 Callee is a function called by another and the


 Caller is a function that calls another function (the callee).

 The values that are passed in the function call are called
the actual parameters.

 The values received by the function (when it is called ) are


called the formal parameters.
Pass by value means that a copy of the actual parameter’s value is
made in memory, i.e. the caller and callee have two independent
variables with the same value. If the callee modifies the parameter
value, the effect is not visible to the caller.

1. Passes an argument by value.


2. Callee does not have any access to the underlying element in the
calling code.
3. A copy of the data is sent to the callee.
4. Changes made to the passed variable do not affect the actual value.

EXAMPLE USING CPP


#include <iostream> EXAMPLE USING JAVA
using namespace std;
public class PassByValue {
intfunc(int a, int b)
public static void main(String[] args) {
{ a = a + b;
int a = 2, b = 3;
cout<<"In func, a = " << a << " b = "<< b <<endl;
return a;//pass by result (out mode) add(a,b);
} System.out.println("Result from main: " +(a+b));
int main()
{ } //5
int x = 5, y = 7;
static void add(int a, int b)
// Passing parameters
{ a = 10;
int z= func(x, y); //pass by value (in mode)
System.out.println("Result from method: " +(a+b));
cout<< "In main, x = " << x << " y = " << y;
}
cout<< "Z =”<<z;
return 0; //13
}

Pass-by-Result:
Pass-by-Result is an implementation model for out-mode parameters.

 When a parameter is passed by result, no value is transmitted to


the subprogram.
 The corresponding formal parameter acts as a local var, but just
before control is transferred back to the caller, its value is
transmitted back to the caller’s actual parameter, which must be a
var.
 One problem with the pass-by-result model is that there can be an
actual parameter collision, such as the one created with the call
sub(p1, p1)
 In sub, assuming that the two formal parameters have different
names, the two can obviously be assigned different values.
 Then whichever of the two is copied to their corresponding actual
parameter last becomes the value of p1.

EXAMPLE USING CPP

using namespace std;

intfunc( )
{
int a= 10, b=20;
a = a + b;
cout<<"In func, a = " << a << " b = "<< b
<<endl;
return b; //pass by result (out mode)
}
int main()
{
// Passing parameters
cout<< "func value:" <<func();
return 0;
}

Pass-by-Value-Result
 It is an implementation model for inout-mode parameters in which
actual values arecopied.
 It is a combination of pass-by-value and pass-by-result.
 The value of the actual parameter is used to initialize the
corresponding formalparameter, which then acts as a local var.
 At subprogram termination, the value of the formal parameter is
transmitted back tothe actual parameter.
 It is sometimes called pass-by-copy because the actual parameter is
copied to theformal parameter at subprogram entry and then
copied back at subprogram termination.

EXAMPLE USING CPP


using namespace std;
intfunc(int a, int b)

{ a = a + b;

cout<<"In func, a = " << a << " b = "<< b <<endl;


return a;//pass by result (out mode)
}
int main()
{
int x = 5, y = 7;

// Passing parameters
Int z= func(x, y); //pass by value (in mode)

cout<< "In main, x = " << x << " y = " << y;


cout<< "Z = <<z;
return 0;
}

Pass-by-reference

 Pass-by-reference is a second implementation model for inout-


mode parameters.
 Rather than copying data values back and forth. This method
transmits an accesspath, sometimes just an address, to the called
subprogram. This provides theaccess path to the cell storing the
actual parameter.
 The actual parameter is shared with the called subprogram.

Advantages:
 The passing process is efficient in terms of time and space.
Duplicate space isnot required, nor is any copying.

Disadvantages:
 Access to the formal parameters will be slower than pass-by-value,
because ofadditional level of indirect addressing that is required.
 Inadvertent and erroneous changes may be made to the actual
parameter.
 Aliases can be created as in C++.

void fun(int&first, int&second)


If the call to fun happens to pass the same var twice, as in
fun(total, total)
Then first and second in fun will be aliases.
#include <stdio.h>
intfnewvalue(int *newvalue);//& to pass by reference
int main()
{
int value = 5;//initialize the variable count
intnewvalue= fnewvalue(&value);// initialize the variable
result
printf("New value: %d\n", newvalue);
printf("value: %d\n", value);
//printf("New value: %d\n", newvalue);
return 0;
}intfnewvalue(int *newvalue)
{ return *newvalue+5;}
Pass-by-Name
 The method is an inout-mode parameter transmission that doesn’t
correspond to asingle implementation model.
 When parameters are passed by name, the actual parameter is, in
effect, textuallysubstituted for the corresponding formal parameter
in all its occurrences in thesubprogram.
 A formal parameter is bound to an access method at the time of the
subprogramcall, but the actual binding to a value or an address is
delayed until the formalparameter is assigned or referenced.
 Because pass-by-name is not used in any widely used language, it is
not discussedfurther here
Subprogram Linkage
 Subprogram linkage refers to the mechanics of communication
between a subprogram invoker (the caller) and the subprogram
itself (the callee).

The caller code consists of a sequence of instructions that:

 sets up parameters,
 sets up a return address,
 jumps to the subprogram start address, and
 deals with the returned value.

The callee code consists of a sequence of instructions that

 implements the subprogram,


 sets up a returned value, and
 jumps to the return address.

You might also like