Subprograms: Subprogram Parameters
Subprograms: Subprogram Parameters
• Subprogram parameters
• Design issues
• Semantic models of parameter passing
• Parameter passing methods:
Call by value
Call by result
Call by reference
Call by value result
Call by name
Pilani Campus
BITS Pilani, Hyderabad Campus
Subprogram
Pass by value:
a=c;
b=d;
temp=a;
a=b;
b=temp;
• a has d’s value and b has c’s value but changes are not passed back to the calling
function so values of c and d are unchanged.
Output:
Consider the call: •List[42]=17 and sub=42(in case of Right-left)
sub=21; •List[21]=17 and sub=42(in case of left-right)
doit(list[sub],sub);
Disadvantages
– Slower accesses (compared to pass-by-value) to formal parameters because
indirect addressing
– If one-way communication is required to the called subprogram, then erroneous
changes might occur in the actual parameters.
– Unwanted aliases (access broadened): Access path is available to the called
subprograms thus providing access to non-local variables. Examples:
void fun (int &first, int &second) , fun(total, total)
int *global;
void main () {
sub(global);
}
void sub(int *param)
{ …}
Pass by reference:
a=&c;
b=&d;
temp=*a;
*a=*b;
*b=temp;
• c and d values are interchanged.
Procedure swap(a,b)
• Effect of the Call swap(x,y) int a,b,temp;
temp = x; Begin
temp = a;
x =y;
a = b;
y = temp; b = temp;
• Output: End;
x=7 x=5,y=7;
y=5 swap(x,y);
int n;
void p(int k) Output:
Call-by-value: 1 1
{ Call-by-reference: 5 5
n=n+1; Call-by-value-result: 1 4
k=k+4;
printf(“%d”, n);
}
main()
{
n=0;
p(n);
printf(“%d”, n);
}
Procedure swap(a,b)
• Effect of call swap(i, x[i])
int a,b,temp;
temp = i;
Begin i = x[i];
temp = a; x[i] = temp;
a = b;
b = temp; • Value of i=5
End; • Value of x[0]=1
• Value of x[1]=3
• Value of x[2]=5
• Value of x[3]=7
i=2 • Value of x[4]=9
X ={1,3,5,7,9,11} • Value of x[5]=2
swap(i, x[i]);