2.passing Parameters To Functions
2.passing Parameters To Functions
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
2
– Pass-by-value
– Pass-by-reference with reference
arguments (pass by reference)
– Pass-by-reference with pointer arguments
(pass by address)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
3
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
4
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
5
void main()
{
cout<<sum(2,3); //5 is displayed
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
6
void main()
{
int x;
sum(2,3,x);
cout<<x; //5 is displayed
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
7
void main()
{
int x;
sum(2,3,&x);
cout<<x; //5 is displayed
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
8
Example (2)
void main()
{
int a=2, b=3;
cout<<"Originally in main a= "<<a<<" and b=
"<<b<<endl;//2 3
exchange(a,b);
cout<<"Later in main a= "<<a<<" and b= "<<b<<endl;//2 3
} © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
9
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
10
void main()
{
int a=2, b=3;
exchange(a,b);
cout<<a<<" "<<b; //3 2
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11
Example (3)
void main()
{
int number = 5;
cout<<number<<endl; //5 is displayed
number = cubeByValue( number );
cout<<number; //125 is displayed
return n * n * n;
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
}
12
number n
5 5
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
13
B) Cubing a Number Passing By Address
#include <iostream.h>
void cubeByaddress( int *b );
void main()
{
int number = 5;
cout<<number<<endl; //5 is displayed
cubeByaddress( &number );
cout<<number; //125 is displayed
}
void cubeByaddress( int *nPtr )
number
5
nPtr
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
15
C) Cubing a Number Passing By Reference
#include <iostream.h>
void cubeByreference( int & );
void main()
{
int number = 5;
cout<<number<<endl; //5 is displayed
cubeByreference( number );
cout<<number //125 is displayed
}
n = n * n * n;
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16
number &n=0x009878
5 5
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.