Sunteți pe pagina 1din 31

Functions and Parameter Passing

Week #4
Top-Down Design
 Proceeds from the original problem at the top
level to subproblems at each lower level
 Case Study: Draw human stick, figure below:
*
* *
* *
/\
/ \
/ \
------
/\
/ \
/ \
Draw human stick
 We can draw this figure with
these four basic components:
 a circle (head) *
* *
 a triangle * *
 intersecting lines /\
 a base line / \
/ \
 intersecting lines ------
/\
/ \
/ \
Structure Chart for Drawing a Stick Figure

Draw
human
Original Problem
stick

Draw
Draw a Draw a
Subproblems intersecti
circle triangle
ng lines

Draw
Draw a
Detailedintersecti
subproblems
base
ng lines
Function (without Arguments)
 Function Prototype
 Form : ftype fname(void);
 Example : void draw_circle(void);
 Function Call Statement
 Syntax : fname();
 Example : draw_circle();
Function (without Arguments)
Example:
Function
/*
Definition * Displays a block-letter H
*/
Syntax: void
ftype fname (void) print_h(void)
{
{
printf("** **\n");
local printf("** **\n");
declarations printf("*****\n");
executable printf("** **\n");
statements printf("** **\n");

} }
The Arguments of a Function
 The arguments of a function are used to carry
information into the function subprogram from
the main function (or from another function
subprogram) or to return multiple results
computed by a function subprogram
 Arguments that carry information into the
function subprogram are called input
arguments; arguments that return results are
called output arguments .
Program to Draw a Human Stick Figure
1. /* 15. int main(void)
2. * Draw a human stick figure 16. {
3. */ 17. /* Draw a circle */
4. #include <stdio.h> 18. draw_circle();
5. 19. /* Draw a triangle */
6. /* function prototypes */ 20. draw_triangle();
7. /* Draws a circle */ 21. /* Draw intersecting lines */
8. void draw_circle(void); 22. draw_intersect();
9. /* Draws intersecting lines */ 23. return(0);
10. void draw_intersect(void); 24. }
11. /* Draws a base line */
12. void draw_base(void);
13. /* Draws a triangle */
14. void draw_triangle(void);
Program to Draw a Human Stick Figure
25. /* 43. /*
26. * Draws a circle 44. * Draws a base line
27. */ 45. */
28. void draw_circle(void) 46. void draw_base(void)
29. { 47. {
30. printf(" * \n"); 48. printf("------- \n");
31. printf("* * \n"); 49. }
32. printf(" * * \n"); 50.

33. } 51. /*
34. /* 52. * Draws a triangle
35. * Draws intersecting lines 53. */
36. */ 54. void draw_triangle(void)
37. void draw_intersect(void) 55. {
38. { 56. draw_intersect();
39. printf(" /\\ \n"); 57. draw_base();
40. printf(" / \\ \n"); 58. }
41. printf("/ \\ \n");
42. }
Program Style
 Use of Comments in a Program with Functions
 Order of Execution of Function Subprograms and Main
Function:
 Because the prototypes for the function subprograms
appear before the main function, the compiler processes
the function prototypes before it translates the main
function. The information in each prototype enables the
compiler to correctly translate a call to that function. The
compiler translates a function call statement as a transfer
of control to the function.
 After compiling the main function, the compiler translates
each function subprogram. During translation, when the
compiler reaches the end of a function body, it inserts a
machine language statement that causes a transfer of
control back from the function to the calling statement.
Program Style
Advantages of Using Function Subprograms
 Procedural Abstraction
 Reuse of Function Subprograms
Displaying User Instructions
1. /*
2. * Displays instructions to a user of program to compute
3. * the area and circumference of a circle.
4. */
5. void instruct(void)
6. {
7. printf("This program computes the area\n");
8. printf("and circumference of a circle.\n\n");
9. printf("To use this program, enter the radius of\n");
10. printf("the circle after the prompt: Enter radius>\n");
11. }
Function (with Input Arguments)
 Function Definition
 Syntax : function interface comment
ftype fname(formal parameter declaration list)
{
local variable declarations
executable statements
}
 Example : /*
* Finds the cube of its argument.
* Pre: n is defined
*/
int cube(int n)
{
return(n*n*n);
}
Function with Multiple Arguments
 Example:
1. /*
2. * Multiplies its first argument by the power of 10
3. * specified by its second argument.
4. * Pre: x and n are defined and math.h is included
5. */
6. double scale(double x, int n)
7. {
8. double scale_factor; /* local variable */
9. scale_factor = pow(10,n);
10. return(x*scale_factor);
11. }

 Function call:
scale(2.5,2);
Functions with Output Parameters
 So far, we know how to pass inputs to a
function and how to use the return statement
to send back one result value from a function
 This section describes how programmers use
output parameters to return multiple results
from a function
 We can use the address of operator ( & ) to
store the actual parameter’s address instead
of its value
Function separate with Multiple Results
/*
* Separates a number into three parts: a sign (+, -, or blank),
* a whole number magnitude, and a fractional part.
*/
void
separate(double num, /* input - value to be split */
char *signp, /* output - sign of num */
int *wholep, /* output - whole number magnitude of num */
double *fracp) /* output - fractional part of num */

signup

num Separate wholep


fracp
Example Functions with Output Parameters
1. /*
2. * Separates a number into three parts: a sign (+, -, or blank),
3. * a whole number magnitude, and a fractional part.
4. */
5. void separate(double num, /* input - value to be split */
6. char *signp, /* output - sign of num */
7. int *wholep, /* output - whole number magnitude of num */
8. double *fracp) /* output - fractional part of num */
9. {
10. double magnitude; /* local variable - magnitude of num */
11. /* Determines sign of num */
12. if (num < 0)
13. *signp = '-';
14. else if (num == 0)
15. *signp = ' ';
16. else
17. *signp = '+';

18. /* Finds magnitude of num (its absolute value) and


19. separates it into whole and fractional parts */
20. magnitude = fabs(num);
21. *wholep = floor(magnitude);
22. *fracp = magnitude - *wholep;
23. }
Calls a Function with Output Arguments
1. int main(void)
2. {
3. double value; /* input - number to analyze */
4. char sn; /* output - sign of value */
5. int whl; /* output - whole number magnitude of value */
6. double fr; /* output - fractional part of value */
7. /* Gets data */
8. printf("Enter a value to analyze> ");
9. scanf("%lf", &value);
10. /* Separates data value into three parts */
11. separate(value, &sn, &whl, &fr);
12. /* Prints results */
13. printf("Parts of %.4f\n sign: %c\n", value, sn);
. . . . . .
Parameter Correspondence
Function main Function separate
Data Area Data Area
value num
35.81 35.81
7 7
sn signp
? +

wh1 wholep
? 35

fr fracp
? 0.817
magnitude
35.81
7
Meanings of * Symbol
 We have now seen three distinct meanings of the
symbol * . In the first week, we studied its use as the
binary operator meaning multiplication.
 Function separate introduces two additional meanings.
 The * ’s in the declarations of the function’s formal
parameters are part of the names of the parameters’ data
types. These * ’s should be read as “pointer to.” Thus the
declaration char *signp; tells the compiler that the type of
parameter signp is “pointer to char .”
 The * has a completely different meaning when it is used as
the unary indirection operator in the function body. Here it
means “follow the pointer.” Thus, when used in a reference,
*signp means follow the pointer in signp. Notice that the
data type of the reference *signp is char , the data type of
*wholep is int , and the data type of *fracp is double .
Different Kinds of Function Subprograms
(1)
Purpose Function Parameters To Return Result
Type
To compute or Same as Input parameters Function code
obtain as type of hold copies of includes a return
input a single value to be data provided by statement with an
numeric or computed or calling function. expression whose
character obtained. value is the result.
value.
To produce void Input parameters No result is
printed hold copies of returned.
output data provided by
containing calling function.
values of
numeric or
character
arguments.
Different Kinds of Function Subprograms
(2)
Purpose Function Parameters To Return Result
Type
To compute void Input Results are stored
multiple parameters hold in the calling
numeric or copies of data function’s data area
character provided by by indirect
results. calling function. assignment through
Output output parameters.
parameters are No return statement
pointers to is required.
actual
arguments.
To modify void Input/output Results are stored
argument parameters are in the calling
values. pointers to function’s data area
actual by indirect
arguments. assignment through
Input data is output parameters.
accessed by No return statement
indirect is required.
Scope of Names - Example program (1)
1. #define MAX 950
2. #define LIMIT 200
3.

4. void one(int anarg, double second); /* prototype 1 */


5. int fun_two(int one, char anarg); /* prototype 2 */
6.

7. int main(void)
8. {
9. int localvar;
10. . . .
11. } /* end main */
12.
Scope of Names - Example program (2)
13. void one(int anarg, double second) /* header 1 */
14. {
15. int onelocal; /* local 1 */
16. . . .
17. } /* end one */
18.

19. int fun_two(int one, char anarg) /* header 2 */


20. {
21. int localvar; /* local 2 */
22. . . .
23. } /* end fun_two */
Scope of Names
Name Visible in Visible in Visible in
one two main
MAX yes yes yes
LIMIT yes yes yes
main yes yes yes
localvar (in main) no no yes
one (the function) yes no yes
anarg (int) yes no no
second yes no no
onelocal yes no no
fun_two yes yes yes
one (formal parameter) no yes no
anarg (char) no yes no
localvar (in fun_two) no yes no
Formal Output Parameters as Actual
Arguments
 So far, all of our actual arguments in calls to
functions have been either local variables or
input parameters of the calling function.
However, sometimes a function needs to pass
its own output parameter as an argument
when it calls another function.
Function scan_fraction
/*
* Gets and returns a valid fraction as its result
* A valid fraction is of this form: integer/positive integer
* Pre : none
*/
void scan_fraction(int *nump, /* output – numerator */
int *denomp) /* output - denumerator */

nump

void scan_fraction
denomp
Function scan_fraction
1. /*
2. * Gets and returns a valid fraction as its result
3. * A valid fraction is of this form: integer/positive integer
4. * Pre : none
5. */
6. void scan_fraction(int *nump, int *denomp)
7. {
8. char slash; /* character between numerator and denominator */
9. int status; /* status code returned by scanf indicating
10. number of valid values obtained */
11. int error; /* flag indicating presence of an error */
12. char discard; /* unprocessed character from input line */
13. do {
14. /* No errors detected yet */
15. error = 0;
16. /* Get a fraction from the user */
17. printf("Enter a common fraction as two integers separated ");
18. printf("by a slash> ");
19. status = scanf("%d %c%d", nump, &slash, denomp);
20. /* Validate the fraction */
21. if (status < 3) {
22. error = 1;
23. printf("Invalid-please read directions carefully\n");
24. } else if (slash != '/') {
25. error = 1;
26. printf("Invalid-separate numerator and denominator");
27. printf(" by a slash (/)\n");
28. } else if (*denomp <= 0) {
29. error = 1;
30. printf("Invalid—denominator must be positive\n");
31. }
32. /* Discard extra input characters */
33. do {
34. scanf("%c", &discard);
35. } while (discard != '\n');
36. } while (error);
37. }
Data Areas for scan_fraction and Its Caller

Calling Function
Function scan_fraction
Data Area
Data Area
Numerator nump
?

Denominator denomp
?
slash
?

S-ar putea să vă placă și