70 likes | 165 Views
passing by value gives a single value. Data - This too shall pass Thanks Dr. Mullins. passing by reference may give back a value Chapter 4 . *. Passing Data - by Value. passing by value: A copy of a value is passed from the calling function to the called function.
E N D
passing by value gives a single value Data - This too shall pass Thanks Dr. Mullins • passing by reference may give back a value Chapter 4 *
Passing Data - by Value • passing by value:A copy of a value is passed from the calling function to the called function. Can use as temp vars doublePythagorus(double a, double b) { a = a * a; b = b * b; double c = sqrt(a + b); return c; } doublePythagorus(double a, double b) { double c; c = sqrt(a*a + b*b); return c; } 9.0 16.0 3.0 4.0 * *
call to find_max value in first_num is passed value in sec_num is passed Formal params Storing Values into Parameters firstnum= 865; secnum=9090;find_max(firstnum, secnum); find_max(x, y) 865 9090 x y * *
4.0 3.0 c 5.0 Passing Data - by Value • double Pythagorus(double, double); • void main(void) • { double height = 4.0, base = 3.0; • cout << “Hypotenuse = “ << Pythagorus(height, base)<<endl; • . . . • } • double Pythagorus(double a, double b) • { double c; c = sqrt(a*a + b*b); • return c; • } * *
6.4 4.0 3.0 Passing Data - by Value • double Pythagorus(doublea, doubleb) • { double c; • a++; • b++; • c = sqrt(a*a + b*b); • return c; • } c 3.0 6.4 4.0 4.0 5.0 4.03.0 back in main: cout << height; cout << base: *
Passing Data by-value Example • void print_val(int); // function prototype • void main(void) • { int w = 3; • cout <<"w before the function call is "<<w<<‘\n’; • print_val(w); • cout <<"w after the function call is "<<w<<‘\n’; • } • void print_val(int q) • { cout<<"Value passed to the function is "<<q<<endl; • q = q *2; // doubles the value • cout<<"Value at the end of the function is "<< q <<endl; • }
Passing Data by-value Results • Output • w before the function call 3 • Value passed to the function is 3 • Value at the end of the function is 6 • w after the function call is 3