31
Chapter 4 Procedural Abstraction and Functions That Return a Value

Chapter 4 Procedural Abstraction and Functions That Return a Value

Embed Size (px)

Citation preview

Page 1: Chapter 4 Procedural Abstraction and Functions That Return a Value

Chapter 4

Procedural Abstraction and Functions That Return a Value

Page 2: Chapter 4 Procedural Abstraction and Functions That Return a Value

Procedural Abstraction

abstraction: the separation of properties from the actual physical object.

procedural abstraction: separate what the function does from how it does it.

Page 3: Chapter 4 Procedural Abstraction and Functions That Return a Value

Top Down Design

• Working from the general to the specific

• Divide and Conquer– Breaking down a problem into sub problems

and subtasks.– Each subtask is a complete structure that

accomplishes a specific well defined task. – C++ uses functions to complete each task

Page 4: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function

• A body of code to perform a specific task.

• A function that performs a single well-defined task is called a cohesive function.

Page 5: Chapter 4 Procedural Abstraction and Functions That Return a Value

Predefined Functions (Libraries)

• In order to keep the compiler small, C++ groups functions into Libraries that we can include when we need them.

• Library files are called header files. (.h) • When we use the #include directive, the compiler copies

the code of the header file into your program.

• Examples:<iostream> Contains functions used to do input and output<cmath> Contains functions used to do mathematical

computations

Page 6: Chapter 4 Procedural Abstraction and Functions That Return a Value

How To Use Predefined Functions

• Include the library • Use the function name in a function call.

• Function call:– We invoke the function by giving its name and

all relevant information (arguments). – Control passes to the function code, executes

it, returns a value (if any) and returns control to the calling function.

Page 7: Chapter 4 Procedural Abstraction and Functions That Return a Value

Type Casting • static_cast<type> is a predefined function that changes type.

– The use of <type> denotes the new type used to replace the existing type.

• Example: int sum, count;double average;average = static_cast<double> (sum)/count;

• Be sure to put parenthesis around single argument to prevent integer divide and then casting.

• Older form: type (variable) average = double (sum)/count;

Page 8: Chapter 4 Procedural Abstraction and Functions That Return a Value

Programmer Defined Functions

• Your own functions.

• Consists of a two parts: – the function prototype/declaration – the function definition.

• A function is like a small program; it has a body and may return a value.

Page 9: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function As A Small Program

• Calling a function is as running a small program.

• Functions use formal parameter, rather than cin, for input. The arguments to the function are the inputs and they are plugged in the formal parameters.

• Functions can send their outputs to the caller through the return statement.

Page 10: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function prototype/declaration• Syntax: Type_Returned Function_Name (Parameter_List);

• Functions must be declared before use. • Funtion Prototype (FP) associates the function name with the code.• FP tells what type of information is needed (order and type of input

arguments) and determines what type of value it returns (type of result).

• FP has a semicolon at the end.• Parameters the list separated by commas.• Example:

int get_choice (); // empty parameter listdouble compute_area (double len, int wid);

• Always include a comment with the prototype telling what its purpose is. A good function is cohesive - it accomplishes a single, well-defined task.

Page 11: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function prototype/declaration (cont.)

• Formal parameters: placeholder for the real variable – sometimes called dummy parameters.Ex: bool inRange (int choice);

• Only the type of the variables needs to be in the parameter list so formal parameters can be omitted in the prototype but the type must be specified. (not advised)Ex: bool inRange (int);

• FP’s may be anywhere in a program but before the function call.– Above main: the whole program can see and use them– Inside another function: only that function can see and use them– In a header file: Any file including that file can use them

Page 12: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function Definition

• Contains 2 part: function header and function body• Must have formal parameters listed in the function

header• May (usually) be defined:

– Below main– In another .cpp file which is linked to the main program file

• Cannot be within another function • Functions that return a value has a returned type and a

value of that type is computed in the program and is passed back to the calling program by the return statement.

Page 13: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function Definition (Actual code)

• Syntax:Type_Returned Function_Name (Parameter_List) // function header

{

… // function body

}

Page 14: Chapter 4 Procedural Abstraction and Functions That Return a Value

Function Call

• Syntax:aValue = Function_Name (Argument_List);

• The argument list is a way for functions to communicate with each other by passing information.

• When the function is called, the program jumps to the function code and executes it.

• A function is like a small program

Page 15: Chapter 4 Procedural Abstraction and Functions That Return a Value

Functions that return a boolean value

• Often used as a flag to decide what action to take next based on evaluation of a certain condition.

• Example:bool inRange (int choice){

if ((choice < 5) &&(choice >0)) return true;

else return false;

}

Page 16: Chapter 4 Procedural Abstraction and Functions That Return a Value

Passing information into the function (Call-by-Value)

• When the function needs information from the main program or another function to work.

• The function will use the values but not change them.

• The compiler actually makes a copy of the value to use.

• The compiler matches the actual parameters to the dummy parameters in the order given in the function call. If you reverse the order, your program will NOT tell you!!!– int result = subtraction (5, 3);– int result = subtraction (3, 5);

Page 17: Chapter 4 Procedural Abstraction and Functions That Return a Value

Functions with Call_by_Value parameters

• Syntax:Type_returned Function_Name (type para1, … , type paraN);

• The real variables (actual parameters) in the function call are matched with the formal parameters by the order.

• A copy of the value of the variables replaces the formal parameters in the function body.

• Automatic type conversion by implicit conversion through parameter list.

• Call-by-value:– The initial value is protected. – A copy of the value of the actual parameters is used in the function but

the function cannot change the value of the actual variables. • Constants and expressions can be passed into functions using call-

by-value.• The value computed in the function is sent back to the calling

function by the return statement. The function call thus has a value and can be used in computations, etc.

Page 18: Chapter 4 Procedural Abstraction and Functions That Return a Value

Call_by_Value (Example)#include <iostream>using namespace std;int sum (int left, int right); // Function prototypesint main (){

int x, y; // Declare two variables to hold integerscout << "Enter two integers .. seperated by a space: "; // User promptcin >> x >> y;cout << "The sum of the two numbers " << x << " " << y << " is “ << sum(x, y); // Function callcout << endl;return 0; // This program requires a return integer value

}

{int result = left + right;left++;right++;return result;

}

Function definition

int sum (int left, int right) Function header

Function body

Page 19: Chapter 4 Procedural Abstraction and Functions That Return a Value

Call_by_Value Mechanism

• Beginning

??

?

?

xy

ab

• cin >> x >> y;User enter 3 and 4

• sum (x, y); sum (3, 4)

3

4

4

3

Page 20: Chapter 4 Procedural Abstraction and Functions That Return a Value

Why use functions? • To avoid Duplicate code:

– If process needed repeatedly, only code once, call multiple times. (Error checking).

– Can also use in other programs.– Shortens program code.

• To improve maintainability– By improving readability, use descriptive function names – Smaller modules allow easier changes

• To improve modularity, easier to write. – Small tasks easier than larger tasks: Do small parts and link together. – Allows many programmers to work on one program.

• Portability.– Can also use in other programs.

• Clarity– Each subtask clearly defined and their relationship to other parts is

clear.

Page 21: Chapter 4 Procedural Abstraction and Functions That Return a Value

When to use a function

• Operation is used in two or more separate places in a program. – (Company name and address used repeatedly)

• When operation needs to serve more than 1 program.– (need Company name and address in several programs - use

user-made library)

• Operation returns a single value – (calculate total cost)

• Operation can be described as a distinct task – (produce summary output at end of program)

• Program is too long and can be program into separate operations.

Page 22: Chapter 4 Procedural Abstraction and Functions That Return a Value

Functions (Need to Know)

• Must use consistent variable names and constants (usually a system glossary or kept in project library that all use).

• Must understand data flow between functions.

• Must verify flow between functions (order)

Page 23: Chapter 4 Procedural Abstraction and Functions That Return a Value

Procedural Abstraction

• The separation of what the function does from how it does it: (Black Box Analogy)

• We can give structure and order of calling functions without knowing how they do computations.

• Just need to know what they do, what they need to do it; not how they work. (information hiding)

Page 24: Chapter 4 Procedural Abstraction and Functions That Return a Value

Procedural Abstraction (Information)

• Comments: information for the users.– Pre-conditions: Any and all conditions required of the

arguments to the function– Post-conditions: Describe the value that is returned

• Ex:double ConvertCoins (int number, double coinValue);

// Pre-Cond: Get number of coins of 1 type and their value in dollar.

// Post-Cond: The total amount of money converted to dollars and returned.

int ConvertCoins (int number, int coinValue);

// Pre-Cond: Get number of coins of 1 type and their value in cents.

// Post-Cond: The total amount of money converted to cents and returned.

Page 25: Chapter 4 Procedural Abstraction and Functions That Return a Value

Formal Parameter Names

• Type_returned Function_Name (type para1, … , type paraN);

– para1, … paraN are formal parameter names

• Should be descriptive but not too long.• Often have a descriptive suffix like “_par” or prefix like

“f_” or “p”double ConvertCoins (int pNumber, double pCoinValue);

• Can be specific or general depending on the use of the functions.

• Declarations of variables inside the function do not include the formal parameters.

Page 26: Chapter 4 Procedural Abstraction and Functions That Return a Value

Global Variables

• A function is like a small program. Each function is called a block of code.

• Variables declared in main are global to main and can be seen inside main (scope).

• Variables declared above main are global to all and can be seen by any files linked to the main file.

Page 27: Chapter 4 Procedural Abstraction and Functions That Return a Value

Local Variables

• A local variable/constant is declared inside a block designated by {}.– Scope:

• Local data is hidden from any other block/function. • Cannot be corrupted.• If there is a variable with the same name in main,

the local variable takes name precedence inside the function.

– Visibility:• Local data exists only during function call. Dies on

exit.

Page 28: Chapter 4 Procedural Abstraction and Functions That Return a Value

Global and Local Variables#include <iostream>using namespace std;double area (double);double PI = 3.14159; // global variableint main (){

int rad; // Declare a variables to hold radius, local to maincout << "Enter the radius of the circle: "; // User promptcin >> rad;cout << "The area of the circle with radius " << rad << " is “ << area (rad); // Print out a complete report to the screencout << endl;return 0; // This program requires a return integer value

}double area (double pRadius){

double rad = pRadius; return rad*rad*PI;}

Page 29: Chapter 4 Procedural Abstraction and Functions That Return a Value

General Notes on Function Scope• The scope of definition of a function is from the function header to the }

brace (closing brace).

• Local Identifiers defined within that scope are only visible within that scope.

• Different functions can use the same identifiers without conflict.

• Formal parameter names may have the same name or a different name from the actual variables used in the function call. It doesn’t matter. The compiler uses position to decide which value is used in which formal parameter.

• Actual variables must be the same type as the formal parameters they replace (type consistent) or standard conversion rules apply (dangerous).

• For clarity and maintainability, we place all include directives together, followed by all global named constant declarations together, followed by all function prototypes.

• Formal parameters in functions are local to the function. Thus, when we plug in actual parameters, the changes to those parameters are only in effect within the function and will not be permanently changed.

Page 30: Chapter 4 Procedural Abstraction and Functions That Return a Value

Overloading A Function Name

• C++ allows identically named functions within the same scope if the number and type of parameters can distinguish them. It is called OVERLOADING.

• If there are multiple definitions of a function f, then f is considered to be overloaded.

• Ex:int Sum (int n1, int n2);

int Sum (int n1, int n2, int n3);

int Sum (int n1, int n2, int n3, int n4);

• The compiler determines which version of an overloaded function to invoke by matching the number and type of parameters in the function prototype with the function call.

Page 31: Chapter 4 Procedural Abstraction and Functions That Return a Value

Overloaded Functions

• Functions with the same name but different parameter list.double ConvertCoins (int number, double coinValue);

// Pre-Cond: Get number of coins of 1 type and their value.

// Post-Cond: The total amount of money converted to dollars.

int ConvertCoins (int number, int coinValue);

// Pre-Cond: Get number of coins of 1 type and their value in cents.

// Post-Cond: The total amount of money converted to cents.

int ConvertCoins (int number, double coinValue);// Pre-Cond: Get number of coins of 1 type and their value.// Post-Cond: The total amount of money converted to cents.

NOT an overloaded function