Nothing Special   »   [go: up one dir, main page]

Unit 3 PPL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Unit -3

SUBPROGRAM:

A subprogram is defined as a set of statements that can be reused at multiple places in a


program when convenient. This reuse results in multiple types of savings, from memory
space to coding time. Such reuse is also an abstraction, for the analysis of subprograms
computations are restored in a program by a statement that calls the subprogram.

Features of Subprograms

The features of subprograms are as follows −

 A subprogram has a single entry point.


 The caller is suspended during the implementation of the called subprogram.
 Control repeatedly returns to the caller when the called subprogram’s execution
eliminates.

Types of Subprograms

There are two types of subprograms which are as follows −

 Procedures − A procedure is defined as a subprogram that defines parameterized


computations. These computations are executed by an individual call statement.
Procedures represent new statements. For example, because Pascal does not have a
sort statement, a user can develop a procedure to sort arrays of records and use a call
to that procedure in place of the unavailable sort statement.
The general syntax of a procedure in Pascal is given as

PROCEDURE Name of Procedure (formal parameter list); {local declaration section}

BEGIN

{instruction sequence}

END;

{end of procedure}

The declaration implies that a procedure has two parts as the specification and the body. The
procedure specification begins with the keyword PROCEDURE and end with the procedure
name or a parameter list. Parameter declarations are optional. Procedures that take no
parameters are written without parenthesis.
Unit -3
The procedure body begins with the keyword BEGIN and end with the keyword END
followed by an optional procedure name. The procedure body has three elements such as a
declarative part, an executable part, and an optional exceptional handling part.

 Functions − A function is a subprogram that evaluates a value. Functions and


procedures are structured identical, except that
o Functions are semantically modeled on mathematical functions.
o Functions have a RETURN clause.
o Functions produce no side effects i.e., it changes neither its parameters nor any
variables defined outside the function.
The general syntax of a function in C is given as

RETURN TYPE Name of Function (formal parameter list){

local declaration section

……………….

……………….

instruction sequence

A function has two elements as the specification and the body. The function specification
begins with the Return type followed by name of the function and parameter list. The
function body begins with {and ends with}. The function body has three parts such as a
declaration part, an executable part, and an optional exceptional-handling part.

Fundamentals or characteristics of subprogram:

(1) A Subprogram is implemented using the Call & Return instructions in Assembly
Language.

(2) The Call Instruction is present in the Main Program and the Return(Ret) Instruction is
present in the subprogram itself.

(3) It is important to note that the Main Program is suspended during the execution of any
subprogram. Moreover, after the completion of the subprogram, the main program executes
from the next sequential address present in the Program Counter.
Unit -3
(4) For the implementation of any subprogram, a “Stack” is used to store the “Return
Address” to the Main Program . Here, Return Address means the immediately next
instruction address after the Call Instruction in the Main program. This Return Address is
present inside the Program Counter. Thus during the execution of the Call Instruction, the
Program Counter value is first pushed to the Stack as the Return Address and then the
Program Counter value is updated to the given address in the Call Instruction. Similarly,
during the execution of Return(Ret) Instruction, the value present in the stack is popped and
the Program Counter value is restored for further execution of the Main Program.

(5) The Main advantage of Subprogram is that it avoids repetition of Code and allows us to
reuse the same code again and again.

SCOPE AND LFETIME OF A VARIABLE:

Scope of a variable
The scope of a vriable is the part of the program for which the declaration is in effect.

In Java, the scope of such a variable is from its declaration to the end of the method.

Lifetime of a variable
The lifetime of a variable is the time period in which the variable has valid memory.

In Java, the lifetime of a variable is the period of time beginning when the method is entered
and ending when execution of the method terminates.

Types of Scope of a varibale:


 Local scope: “visible” within function or statement block from point of declaration until
the end of the block.
 Global scope: visible everywhere unless “hidden”.
 Class scope: “seen” by class members.
 Namespace scope: visible within namespace block.
 File scope: visible within current text file.
Type with lifetime of variable:
 Static: A static variable is stored in the data segment of the “object file” of a program. Its
lifetime is the entire duration of the program’s execution.
Unit -3
 Automatic: An automatic variable has a lifetime that begins when program execution
enters the function or statement block or compound and ends when execution leaves the
block. Automatic variables are stored in a “function call stack”.
 Dynamic: The lifetime of a dynamic object begins when memory is allocated for the
object (e.g., by a call to malloc() or using new) and ends when memory is deallocated (e.g.,
by a call to free() or using delete). Dynamic objects are stored in “the heap”.
STATIC SCOPE AND DYNAMIC SCOPE:

The scope of a variable x in the region of the program in which the use of x refers to its
declaration. One of the basic reasons for scoping is to keep variables in different parts of the
program distinct from one another. Since there are only a small number of short variable
names, and programmers share habits about naming of variables (e.g., I for an array index), in
any program of moderate size the same variable name will be used in multiple different
scopes.

Scoping is generally divided into two classes:

1. Static Scoping

2. Dynamic Scoping

Static Scoping:

Static scoping is also called lexical scoping. In this scoping, a variable always refers to its
top-level environment. This is a property of the program text and is unrelated to the run-time
call stack. Static scoping also makes it much easier to make a modular code as a programmer
can figure out the scope just by looking at the code. In contrast, dynamic scope requires the
programmer to anticipate all possible dynamic contexts.

In most programming languages including C, C++, and Java, variables are always statically
(or lexically) scoped i.e., binding of a variable can be determined by program text and is
independent of the run-time function call stack.

For example, the output for the below program is 10, i.e., the value returned by f() is not
dependent on who is calling it (Like g() calls it and has a x with value 20). f() always returns
the value of global variable x.

// A C program to demonstrate static scoping.


Unit -3
#include<stdio.h>

int x = 10;

// Called by g()

int f()

return x;

// g() has its own variable

// named as x and calls f()

int g()

int x = 20;

return f();

int main()

printf("%d", g());

printf("\n");

return 0;

Output :

10

To sum up, in static scoping the compiler first searches in the current block, then in global
variables, then in successively smaller scopes.
Unit -3
Dynamic Scoping:

With dynamic scope, a global identifier refers to the identifier associated with the most recent
environment and is uncommon in modern languages. In technical terms, this means that each
identifier has a global stack of bindings and the occurrence of an identifier is searched in the
most recent binding.

In simpler terms, in dynamic scoping, the compiler first searches the current block and then
successively all the calling functions.

// Since dynamic scoping is very uncommon in

// the familiar languages, we consider the

// following pseudo code as our example. It

// prints 20 in a language that uses dynamic

// scoping.

int x = 10;

// Called by g()

int f()

return x;

// g() has its own variable

// named as x and calls f()

int g()

int x = 20;

return f();

}
Unit -3
main()

printf(g());

Output in a language that uses Dynamic Scoping :

20

Static Vs Dynamic Scoping

In most programming languages static scoping is dominant. This is simply because in static
scoping it’s easy to reason about and understand just by looking at code. We can see what
variables are in the scope just by looking at the text in the editor.

Dynamic scoping does not care about how the code is written, but instead how it executes.
Each time a new function is executed, a new scope is pushed onto the stack.

Perl supports both dynamic and static scoping. Perl’s keyword “my” defines a statically
scoped local variable, while the keyword “local” defines a dynamically scoped local variable.

# A perl code to demonstrate dynamic scoping

$x = 10;

sub f

return $x;

sub g

# Since local is used, x uses

# dynamic scoping.

local $x = 20;
Unit -3
return f();

print g()."\n";

Output : 20

DESIGN ISSUES OF SUBPROGRAMS:

 Are local variables static or dynamic?


 Can subprogram definitions appear in other subprogram definitions?
 What parameter-passing method or methods are used?
 Are the types of the actual parameters checked against the types of the formal parameters?
 If subprograms can be passed as parameters and subprograms can be nested,
 what is the referencing environment of a passed subprogram?
 Can subprograms be overloaded?
 Can subprograms be generic?
 If the language allows nested subprograms, are closures supported?
LOCAL REFERENCING ENVIRONMENTS:
Local Variables
 Vars that are defined inside subprograms are called local vars.
 Local vars can be either static or stack dynamic.
 By default an variable in stack dynamic.
Advantages of using stack dynamic variable:

a. Support for recursion.


b. Storage for locals is shared among some subprograms.

Disadvantages of using stack dynamic variable:


a. Allocation/deallocation time required.
b. Indirect addressing “only determined during execution.”
c. Subprograms cannot be history sensitive “can’t retain data values of local vars
between calls.”
Advantages of using static variable:
Unit -3
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 of using static variable:
a. Inability to support recursion.
b. Their storage can’t be shared with the local vars of other inactive subprograms.
Example for stack dynamic variable:
int addition(int a, int b) {
int sum = 0;
sum = a+b;
return sum;
}

Example for static variable:


//static variable uses static keyword
int addition(int a, int b) {
static int sum = 0;
sum = a+b;
return sum;
}

PARAMETER PASSING METHODS

Parameter-passing methods are the ways in which parameters are transmitted to and/or from
called subprograms.
Parameter passing depends on model of subprogram.There are two models for parameter
passing-
1. Semantics Models of Parameter Passing
2. Implementation Models of Parameter Passing
1. Semantics Models of Parameter Passing: Formal parameters are characterized by one of
three distinct semantics models:
Unit -3
1. They can receive data from the corresponding actual parameter, called in mode.
2. They can transmit data to the actual parameter, called out mode.
3. They can do both, called inout mode.
2. Implementation Models of Parameter Passing: This model consist the following ways
of parameter passing.
1. Pass by value
2. Pass by reference
3. Pass-by-Result
4. Pass-by-Value-Result
5. Pass-by-Name
1. Pass by value: Value of actual parameter in read only mode is transmitted to formal
parameters.
2. Pass by reference: Reference/address of actual parameter is transmitted to formal
parameters.
3. Pass-by-Result: When a parameter is passed by result, no value is transmitted to the
subprogram.
4. Pass-by-Value-Result: Pass-by-value-result is an implementation model for inout-mode
parameters. Pass-by-value-result is sometimes called pass-by-copy, because the actual
parameter is copied to the formal parameter at subprogram entry and then
copied back at subprogram termination.
5. Pass-by-Name: Pass-by-name is an inout-mode parameter transmission method. In
it parameters are passed by name. Implementing a pass-by-name parameter requires a
subprogram to be passed to the called subprogram to evaluate the address or value of the
formal parameter.
Program examples:
Call by value:
#include <iostream>

using namespace std;

void show(int x)
{
cout<<x<<endl;
Unit -3
}
int main()
{
int age = 20;
show(age);
show(10);

return 0;
}

Call by reference:

#include <iostream>
using namespace std;

void show(int *x)


{
cout<<*x<<endl;
}
int main()
{
int age = 20;
show(&age);

return 0;
}

OVERLOADED SUB-PROGRAMS

Subprogram means nothing but a function or procedure in a programming language.


An overloaded subprogram is a subprogram that has the same name as another subprogram in
the same referencing environment.
Unit -3
A subprogram must be different from the others in the number, order, or types of its
parameters, and possibly in its return type if it is a function.

The meaning of a call to an overloaded subprogram is determined by the actual parameter list
(and/or possibly the type of the returned value, in the case of a function).
Overloaded subprograms have same name but not necessry have same process.
For example overloaded subprogram in C++:
#include <iostream>
using namespace std;
void show (int a)
{
cout << a ;
}

void show (int a, int b)


{
cout << a << b;
}
int main()
{
int a = 10;
int b = 20;
show(a);
show(a, b);
return 0;
}

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.
 Parametrically polymorphic subprograms are often called generic subprograms.
 C++ provide a kind of compile-time parametric polymorphism.
For example Generic Functions in C++:
Unit -3
template <class Type>
void show(Type a) {
cout<<a;
}
void main()
{
show(10);
show(10.2);
show(‘c’);
}

Overloading operators (C++ and ada only)

You can redefine or overload the function of most built-in operators in C++. These operators
can be overloaded globally or on a class-by-class basis. Overloaded operators are
implemented as functions and can be member functions or global functions.

An overloaded operator is called an operator function. You declare an operator function with
the keyword operator preceding the operator. Overloaded operators are distinct from
overloaded functions, but like overloaded functions, they are distinguished by the number and
types of operands used with the operator.

Consider the standard + (plus) operator. When this operator is used with operands of different
standard types, the operators have slightly different meanings. For example, the addition of
two integers is not implemented in the same way as the addition of two floating-point
numbers. C++ allows you to define your own meanings for the standard C++ operators when
they are applied to class types. In the following example, a class called complx is defined to
model complex numbers, and the + (plus) operator is redefined in this class to add two
complex numbers.

This example illustrates overloading the plus (+) operator.

#include <iostream>

using namespace std;

class complx

{
Unit -3
double real,

imag;

public:

complx( double real = 0., double imag = 0.); // constructor

complx operator+(const complx&) const; // operator+()

};

// define constructor

complx::complx( double r, double i )

real = r; imag = i;

// define overloaded + (plus) operator

complx complx::operator+ (const complx& c) const

complx result;

result.real = (this->real + c.real);

result.imag = (this->imag + c.imag);

return result;

int main()

complx x(4,4);

complx y(6,6);

complx z = x + y; // calls complx::operator+()


Unit -3
}

DESIGN ISSUES FOR FUNCTIONS

The following design issues are specific to functions:


1. Are side effects allowed?
2. What types of values can be returned?
3. How many values can be returned?
1. Functional Side Effects: Because of the problems of side effects of functions that are called
parameters to functions should always be in-mode (actual to formal parameter).
This requirement of in mode parameter passing prevents a function from causing side effects
through its parameters.

COROUTINES

To understand coroutines first we should know about subroutines.


In computer programming, a subroutine is a sequence of program instructions that perform a
specific task. For example a program for addition, subtraction. Subroutines is also known as

function.
Unit -3
Coroutines are generalizations of the subroutines.
A subroutine has the same starting point and the same endpoint all the time, while a coroutine
has multiple entry points for suspending and resuming execution. Coroutines are cooperative,
that means if a coroutine consume input data, another coroutine can consume it, and another
coroutine can be used to display the output.
Coroutines are nothing but cooperative functions.

You might also like