08 Functions and Parameters Passing.pptx - Topic 8 Functions and Parameter-Passing 1 Parameter Passing Pass-by-Value When a function is called the value

# 08 Functions and Parameters Passing.pptx - Topic 8...

• 48

This preview shows page 1 - 14 out of 48 pages.

Topic 8 Functions and Parameter-Passing 1
Parameter Passing: Pass-by-Value When a function is called, the value of the actual parameter is copied to the formal parameter. This method of parameter-passing is called pass by value . 2
Parameter Passing: Pass-by-Value Example – void function with parameter : display_rboxed(135.68) ; Function call with actual parameter value 135.68 Function definition with formal parameter rnum void display_rboxed( double rnum ) { cout << "**********\n"; cout << "* *\n"; cout << "* " << fixed << setprecision(2) << setw(6) << rnum << " *\n"; cout << "* *\n"; cout << "**********\n"; } 3
Parameter Passing: Pass-by-Value Example – void function with parameter : display_rboxed(135.68) ; 135.68 rnum gets copy of the actual parameter value 135.68 rnum void display_rboxed( double rnum ) { cout << "**********\n"; cout << "* *\n"; cout << "* " << fixed << setprecision(2) << setw(6) << rnum << " *\n"; cout << "* *\n"; cout << "**********\n"; } 4
Parameter Passing: Pass-by-Value Example – non-void function with parameter : double radius = 10.0; double area = compute_area(radius); double compute_area (double r) { return (PI * pow(r,2)); } Function call with actual parameter radius Function definition with formal parameter r 5
Parameter Passing: Pass-by-Value Example – non-void function with parameter : radius = 10.0; area = compute_area(radius); double compute_area (double r) { return (PI * pow(r,2)); } 10.0 10.0 r r gets copy of actual parameter value 6 double radius = 10.0; double area = compute_area(radius);
Parameter Passing: Pass-by-Value Example – non-void function with parameter : double compute_area (double r) { return (PI * pow(r,2)); } Result returned to calling function 7 double radius = 10.0; double area = compute_area(radius);
Functions and Results A function may have a return value but no parameters. For example, a function that accepts a data value from the user and passes back the value to the calling function. 8