Download presentation
Presentation is loading. Please wait.
Published byTheodore Garrett Modified over 9 years ago
1
Chapter 06 (Part I) Functions and an Introduction to Recursion
2
Objectives In part I you will learn: To construct programs modularly from functions. To create a user-defined function. To use common math functions available in the C++ Standard Library.
3
6.1 Introduction Functions –Facilitate the design, implementation, operation and maintenance of large programs Divide and conquer technique –Construct a large program from small, simple pieces (e.g., components)
4
Functions in Mathematics Let be a function of, where –Questions: What does ‘ ‘ exactly mean? How do you compute 3 + f (2)? –The expression ‘3 + f (2)’ invokes/calls the function by giving 2 as argument.
5
Functions The ‘ f ’ in f ( x ) is called function name. The ‘ x ’ in f ( x ) is called parameter ( 參數 ) of the function f. The expression,, defines the output type and input type of the function. –For example, f (1.23) is invalid. InputOutput x ParameterBody Type: Z Return Value
6
Functions How do you compute 3 + f (2)? –The expression ‘3 + f (2)’ invokes/calls the function f by giving 2 as argument ( 引數 ). –In f ( x ), The parameter x is assigned the value of the argument and substituted into the equation in the body. –The function returns the computation result which substitutes into ‘3 + f (2)’.
7
6.2 Program Components in C++ Functions –Also called methods or procedures –Allow programmers to modularize a program by separating its tasks into self-contained units
8
Functions in C++ The basic structure of a function in C++ must include: Function name Use braces to enclose the body of a function (Remember to indent the body) Body Parameter declaration (name and type)
9
Function in C++ The return type of a function –If the return type is defined, there must be a return- statement before the program terminates. The type of return value must be coincident with the declaration of the function.
10
Function in C++ If the function has no parameter and no return value: –Use void as its return type Return statement is not required if the return type is void. However, a return statement without any return value can be used to terminate the execution immediately.
11
Main Function in C++ In C++, the main function is where a program starts execution. No parameter. If main function has return value, type must be int. Return 0 to indicate the execution successfully terminates. Otherwise, return -1 to indicate program terminates abnormally.
12
6.2 Program Components in C++ A function is invoked by a function call –Called function either returns a result or simply returns to the caller. –Function calls form hierarchical relationships
13
Interaction between Functions The main() is called main function; other functions are called sub-function or user-defined function. Prototype / function declaration
14
Function Call Suppose s is assigned by 3. int result = 2 + f(s); Copy value Output x Parameter int value Return Value Call / Invoke the sub-function f(). S argument int x3 int value = x*x + 2*x + 5; 20 The variable, result, is assigned by the computation result of 2 + 20, which is 22.
15
Fig. 6.1 | Hierarchical Boss Function/Worker Function Relationship
16
6.4 Function Definitions with Multiple Parameters Multiple parameters –Functions often require more than one piece of information to perform their tasks –Specified in both the function prototype and the function header as a comma-separated list of parameters Parameters Return Value Parameters can be multiple. Note, there is at most 1 return value.
17
Example Parameters are separated by comma
18
6.4 Function Definitions with Multiple Parameters Compiler uses a function prototype to: –Check that calls to the function contain the correct number and types of arguments in the correct order –Ensure that the value returned by the function is used correctly in the expression that called the function Each argument must be consistent with the type of the corresponding parameter
19
Common Programming Error Declaring method parameters of the same type as double x, y instead of double x, double y is a syntax error—an explicit type is required for each parameter in the parameter list. Example: –Incorrect: int max (int x, y) { …… } int max (int x, int y) { …… }
20
Common Programming Error 6.2 Compilation errors occur if the function prototype, function header and function calls do not all agree in the number, type and order of arguments and parameters, and in the return type. Error! Why?
21
6.4 Function Definitions with Multiple Parameters Three ways to return control to the calling statement: –If the function does not return a result: Program flow reaches the function-ending right brace or Program executes the statement return; –If the function returns a result: Program executes the statement return expression ; –expression is evaluated and its value is returned to the caller
22
★ The Scope of Variables The only way to interact with a function is through its parameters and return value. The variables declared in a function cannot be seen by other functions. Copy value Output x Parameter int value Return Value S argument int x int value = x*x + 2*x + 5; The variable declared here can only be used by the function itself.
23
6.2 Program Components in C++ Advantages of functions –Statements in function bodies are written only once Reused from perhaps several locations in a program Hidden from other functions Avoid repeating code –Enable the divide-and-conquer approach –Reusable in other programs –User-defined or programmer-defined functions
24
Software Engineering Observation 6.2 To promote software reusability, every function should be limited to performing a single, well-defined task. The name of the function should express that task effectively. Such functions make programs easier to write, test, debug and maintain. A small function that performs one task is easier to test and debug than a larger function that performs many tasks.
25
6.2 Program Components in C++ C++ Standard Library –Rich collection of functions for performing common operations, such as: Mathematical calculations String manipulations Character manipulations Input/Output Error checking –Provided as part of the C++ programming environment
26
6.3 C++ Library Functions Global functions –Do not belong to a particular class –Have function prototypes placed in header files Can be reused in any program that includes the header file and that can link to the function’s object code –Example: sqrt in header file sqrt( 900.0 ) All functions in are global functions
27
Fig. 6.2 | Math library functions.
28
6.5 Function Prototypes and Argument Coercion Function prototype –Also called a function declaration –Indicates to the compiler: Name of the function Type of data returned by the function Parameters the function expects to receive –Number of parameters –Types of those parameters –Order of those parameters
29
Software Engineering Observation 6.6 Function prototypes are required in C++. Use #include to obtain function prototypes for the C++ Standard Library functions from the header files for the appropriate libraries.
30
Common Programming Error 6.3 If a function is defined before it is invoked, then the function’s definition also serves as the function’s prototype. If a function is invoked before it is defined, and that function does not have a function prototype, a compilation error occurs.
31
Example Prototype / function declaration
32
Compilation Error max is not declared!
33
Software Engineering Observation 6.7 Always provide function prototypes –Providing the prototypes avoids tying the code to the order in which functions are defined (which can easily change as a program evolves).
34
6.5 Function Prototypes and Argument Coercion Function signature (or simply signature) –The portion of a function prototype that includes the name of the function and the types of its arguments Does not specify the function’s return type –Functions in the same scope must have unique signatures The scope of a function is the region of a program in which the function is known and accessible
35
Common Programming Error 6.4 It is a compilation error if two functions in the same scope have the same signature but different return types. Accepted: double max(double x, double y); int max(int x, int y); Incorrect: double max(double x, double y); int max(double x, double y); Signatures are different. Signatures are duplicated.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.