Presentation is loading. Please wait.

Presentation is loading. Please wait.

2011/11/10: Lecture 21 CMSC 104, Section 4 Richard Chang

Similar presentations


Presentation on theme: "2011/11/10: Lecture 21 CMSC 104, Section 4 Richard Chang"— Presentation transcript:

1 2011/11/10: Lecture 21 CMSC 104, Section 4 Richard Chang
Functions Review 2011/11/10: Lecture 21 CMSC 104, Section 4 Richard Chang [Based on dblock spr’06lecture, slightly modified]

2 Expressions An expression gives a value and can be
a constant (e.g., 3) the value stored in a variable (e.g., x ) the result of an operation (e.g., 3 + 4) the return value of a function (e.g., sqrt(5) ) any combination of the above: x + sqrt( 7 * 4) - 1

3 Functions The name of a function can appear in 3 places:
a function prototype the implementation of a function a function call Each has a different syntax!!!

4 Function Prototypes Function prototypes tell the compiler:
the name of a function the type of the return value (if any) the types of the formal parameters (if any) double average (int n, int m) ; void print_this () ; void PrintLabel) (int year) ;

5 Function Prototypes Function prototypes appear in:
the beginning of a .c file inside a header file (a .h file) If you use a function in a file, the function prototype for that function should be present in one of these two ways (not both). If the prototype is in a .h file, it must be included using #include.

6 Function Implementation
The function implementation: has the actual C program for the function can appear in a separate file from where the function is called. type of the return value and parameters must match types in the function prototype. for separate compilation, include the .h file so the compiler can check type compatibility.

7 Function Implementation
type functionName ( type param, type param, ...) { variable declarations statements }

8 Function Call A function call:
must include actual parameters (arguments) that match the function prototype in number and type: x = average(a, b) ; actual parameters can be expressions: x = average(a + 7, 2 * b) ; does not include any type declarations!

9 Function Call (cont’d)
A function call: has a return value that can be used in an expression: x = 2 * average(a, b) - 5 ; x = 2 * average( add5(a), b + 1 ) - 5 ;

10 Function Call (cont’d)
A function call: has a return value that can be ignored: scanf (“%d”, &n) ; without a return value cannot be used in an expression: PrintLabel (year) ;


Download ppt "2011/11/10: Lecture 21 CMSC 104, Section 4 Richard Chang"

Similar presentations


Ads by Google