Passing Parameters

Download Report

Transcript Passing Parameters

Passing Parameters
Different Techniques
•
•
•
•
•
Pass by Value
Pass by Reference
Pass by Result
Pass by Value-Result
Pass by Name
Pass By Value
• Make a copy of the value
• Send the copy to the function
• Result NOT transmitted back
void test(int A)
{A++;}
//2
void main()
{ int B=5; //1
test(B);
cout << B;//3
}
A
B
----
5
5
5
//2
6
5
//3
----
5
//1
(entry)
Pass By Result
• No input value
• Send the copy to the function
• Result transmitted back on return
void test(int A)
{A++;}
//2
void main()
{ int B=5; //1
test(B);
cout << B;//3
}
A
B
----
5
?
5
//2
?+1
5
//3
----
//1
(entry)
?+1
Pass By Value Result
• Copy of input value
• Use the copy in the function
• Result transmitted back on return
void test(int A)
{A++;}
//2
void main()
{ int B=5; //1
test(B);
cout << B;//3
}
A
B
----
5
5
5
//2
6
5
//3
----
6
//1
(entry)
Pass By Reference
• Send address of original
• Use pointer inside function
• No need to do explicit return
void test(int A)
{A++;}
//2
void main()
{ int B=5; //1
test(B);
cout << B;//3
}
A
B
//1
----
5
(entry)
*B
5
//2
*B
6
//3
----
6
Pass By Name
• Conceptual model is to substitute
name of the actual parameter for the
formal parameter
• Functions like reference in MOST
cases
• When passing parameters like i,a[i]
different results occur
Procedure BIGSUB
integer GLOBAL;
integer array LIST[1:2];
procedure SUB(PARAM)
begin
PARAM:=1;
GLOBAL:=GLOBAL+1;
PARAM:=5;
end;
begin
LIST[1]:= 2;
LIST[2]:= 2;
GLOBAL :=1;
SUB(LIST[GLOBAL])
end;
Substitute actual for formal
Looks like only 2 changes
in the procedure.
First assignment to PARAM
appears to have no effect!
Actually updates
LIST[1] -> 1
LIST[2] -> 5
and GLOBAL -> 2
Procedure BIGSUB
integer GLOBAL;
integer array LIST[1:2];
procedure SUB(PARAM)
begin
LIST[GLOBAL] :=1;
GLOBAL:=GLOBAL+1;
LIST[GLOBAL] :=5;
end;
begin
LIST[1]:= 2;
LIST[2]:= 2;
GLOBAL :=1;
SUB(LIST[GLOBAL])
end;
Review the examples
in
Section 8.5.8
2-d arrays as parameters
• Recall from earlier notes that 2-d arrays are
– column major or
– row major
• Formula for accessing elements for row major
requires row size in dimension
Loc (a[I,J]) = base address (a)
(I-lb1)*size of row +
(J-lb2)*size element
size of row=number columns allocated *size element
Addressing
• Storage is row-major or column-major order
int A[2,3];
(1,1)
(2,1)
(3,1)
(1,2)
(2,2)
(3,2)
(1,1)
(1,1)
(1,2)
(2,1)
(2,1)
(3,1)
(2,2)
(1,2)
(3,1)
(2,2)
(3,2)
(3,2)
C/C++ does row major
Parameter only showing number
of columns
void fun( int matrix[][10]) {
…}
void main () {
int mat[5][10];
…
fun(mat);
Original dimension 5x10
…
}
Row major is sized by column dimension.
ONLY WORKS IF COLUMN SIZE IS 10!
Other ways of handling 2-d arrays
Some languages such as Ada
store a run-time property for
the dimension
float sumer(float mat[][] ) {
float sum=0.0;
int row;
for(row=0;row<mat.length;row++)
...