470 likes | 639 Views
CIS162AB - C++. Functions Juan Marquez 04_functions.ppt. Overview of Topics. Top-Down Design Structure Charts Predefined Functions Black Box Analogy Programmer Defined Functions Function Prototype, Function Call, Function Definition Variable Scope Local vs Global Function Overloading.
E N D
CIS162AB - C++ Functions Juan Marquez04_functions.ppt
Overview of Topics • Top-Down Design • Structure Charts • Predefined Functions • Black Box Analogy • Programmer Defined Functions • Function Prototype, Function Call, Function Definition • Variable Scope • Local vs Global • Function Overloading
A method where the major task to be accomplished is divided into subtasks. Major Task: clean house Subtasks: dust , vacuum, sweep, mop Major Task: P03 ex Calculate Total Order Subtasks: get price, get quantity, calculate costs, display order Top-Down Design
Subtasks • Each subtask may produce some result. • Treat them as small programs. Input -> Process -> Output • These subtasks can be used at different times in one program or placed in a library and used by many different programs. • cout is a complicated task that displays information to the console, and is used by many different programs.
Structure Chart • Top-Down design is depicted with a structure chart.
Structure Charts • A structure chart is a design tool that shows the overall structure of a program, but omits specific logic. • Structure charts are developed at a much higher level than flowcharts, because they only show what tasks need to be completed, and not how they will be completed. • Flowcharts depict the detail steps of how a task will be completed. • The main benefit is in the initial planning of a program.
Implemented Using Functions • Top-Down design is implemented using functions. • A function is a collection of statements that are grouped together to perform a specific operation. • Before coding some programmer defined functions, let’s look at some predefined functions. • It will help understand what we are trying to develop if we look at how functions are used.
Predefined Functions • Square root function is named sqrt. • The documentation for sqrt states the function name, the type of the value that will be returned, and the type and number of parameters. double sqrt(double); returnType functionName (parameters); • sqrt takes one parameter of the type double. • The function is called using the following syntax:answer = sqrt(num1);
sqrt Example #include <cmath>using namespace std;double num, answer;cout << “Enter a number: “;cin >> num;answer = sqrt(num);cout << “The square root of “ << num << “ is “ << answer;
Function Call • We issue a function call when we use a function. • Processing control is passed to the function until it completes its task and returns control back to the calling function. • Values are passed to functions as arguments. • The words parameter and argument are closely related. Parameter is used with function definitions, and argument is used with function calls. • Many functions return a value back,but only one value can be returned.
Power Function • Functions can only return one value, but may have many parameters.answer = pow (num1, num2); • Raises num1 to the power of num2.In math it would be stated as:answer = num1 num2answer = pow(10.0, 2.0);answer would be equal to 100.00 (10 2 )
Small Programs • Think of each function as a small program with input, process, and output steps. answer = sqrt(num1); returnType = functionName (arguments); Output < Process < Input • An IPO chart and Flowchart can be developed for each function.
Compiler Directives • Predefined functions are stored in header files. • Must be #included by programs using them, or compiler will give syntax error stating function is undeclared. #include <cmath> //sqrt,pow#include <cstdlib> //abs,labsusing namespace std;
Additional Examples • See textbook for additional examples of predefined functions. • Gives library or header file, function name, return type, and parameter types.
Type Casting • Allows us to convert the value in a variable to a desired data type. • sqrt requires a parameter of type double. • If you only have int type variables, you can type cast for the function call:answer = sqrt(double (intNum1)); • Actual value and data type of intNum1 is not affected. • This is very subtle and can be difficult to find a bug or to maintain. Use type casting sparingly.
New Type Casting Syntax • static_cast<Type>(expression) • This command takes expression and returns an equivalent value in the data type specified in Type. • answer = sqrt(static_cast<double>(intNum1));
3 Additional Type Casters • const_cast<Type>(expression) • dynamic_cast<Type>(expression) • reinterpret_cast<Type>(expression) • These have specific purposes and they are not covered in this course .
Black Box Analogy • Many functions are designed as black boxes. • We should not be concerned how the function performs its processing. We only need to know the inputs, outputs, and what it does. • This is also known as Method Abstraction. • double sqrt(double) We know what is required to use it, but we don’t know how it calculates the square root. • Develop your own functions with the Black Box Analogy in mind.
Programmer Defined Functions Three Components 1. Function Prototype 2. Function Call 3. Function Definition
Function Prototype • Before main() to make them global declarations double calcGross(int hours, double rate); //note semicolon
Function Call void main() { int hours; double rate, pay; cin >> hours >> rate; pay = calcGross(hours,rate); cout << pay; } In the function call the variables listed in the parentheses are called arguments, and in the prototype they are call formal parameters.
Function Definition • After main() double calcGross(int hours, double rate) { double gross; gross = hours * rate; return gross; }
Three Parts to Function Definition No semicolon after header.
Function Definition Details • No semicolon after closing parenthesis on header. • Variables used by function must be declared locally. • Variables listed in header are actually declared as local variables. • Statement with function call transfers control to the function being called.
Return Statement • Only one value can be returned through return statement. • The data type of the variable used in the return statement must match the return type specified in header. • Return statement returns the value back to the variable listed to the left of the call statement. • Return statement returns control back to the calling function.
Function Definitions and Prototypes • Function Prototypes are actually NOT required. • Function Definitions may be placed anywhere before being called, so placing definition before main would eliminate prototypes. • But doing this will not work when we get to separate compilations. • It’s best to form a good habit now, so you don’t have to break a bad habit later.
All Together Now double calcGross(int hours, double rate); //prototype void main() { int hours; double rate, pay; cin >> hours >> rate; pay = calcGross(hours,rate);//function call cout << pay; } double calcGross(int hours, double rate) //definition { double gross; gross = hours * rate; return gross; }
Single Return Statement double calcGross(int hours, double rate) { double gross; if (hours > 40) gross = (40 * rate) + ((hours – 40) * rate * 1.5); else gross = hours * rate; return gross; }
Multiple Return Statements double calcGross(int hours, double rate) { if (hours > 40) return ( (40 * rate) + ((hours – 40) * rate * 1.5)); else return (hours * rate); } //In structured programming we usually want one way in, and one way out of a function, so a single return statement is preferred.
Variable Scope • Variable scope – determines in which function or block of code a particular variable exists in. • Let’s look at each the following topics in detail: • Local variables • Call-by-value • Block of code • Global variables
Local Variables • Variables are local to the function in which they are defined. • Variables defined in main() are assigned their own memory and can only be referenced in main(). • Variables defined in calcGross() are assigned their own memory and can only be referenced in calcGross(). • These two functions cannot see or reference each others variables • They have separate memory allocations even though the variable names may be the same.
Memory and Call-by-Value double calcGross(int hours, double rate); //parameters defined as call-by-value void main() parameters. { int hours; double rate, pay; cin >> hours >> rate; pay = calcGross(hours,rate); cout << pay; } double calcGross(int hours, double rate) { double gross; gross = hours * rate; return gross; }
Declare Variables and Functions Values unknown after declaration.
pay = calcGross(hours,rate); Call-by-Value - Values in variables of main are sent to variables of calcGross.
Control Transferred to calcGross double calcGross(int hours, double rate); void main() { int hours; double rate, pay; cin >> hours >> rate; pay = calcGross(hours,rate); //function call cout << pay; } double calcGross(int hours, double rate) { double gross; gross = hours * rate; return gross; }
Return Value and Control to main double calcGross(int hours, double rate); void main() { int hours; double rate, pay; cin >> hours >> rate; pay =calcGross(hours,rate); cout << pay; } double calcGross(int hours, double rate) { double gross; gross = hours * rate; return gross; }
return gross; pay = calcGross(hours,rate); Return sends the value to variable on the left side of the equal sign on the function call statement.
Block of Code • Block – contains single or multiple statements (compound) and is defined with an open and close brace {}. • The variables declared in a block are local to the block. • Examples of blocks • Function block • Loop block • If statement block • Anywhere open and close braces are used.
Two Blocks of Code double calcGross(int hours, double rate); void main() { int hours; double rate, pay; cin >> hours >> rate; pay = calcGross(hours,rate); cout << pay; } double calcGross(int hours, double rate) { double gross; gross = hours * rate; return gross; }
Global Variables • Global variables are defined before main and they can be referenced by all the functions in the program. • Good use is for constants that store rates, or a company name. (FICA_RATE, OVERTIME_RATE, COMPANY_NAME, etc.) • A value that is the same in many different programs.
Global Variable No-no • Do not make variables whose values change during the execution of the program global variables. • It may seem easier to use global variables, but it will actually lead to bad programming practices and cause you problems as we begin developing programs using functions and separate compilations.
Global Example double calcGross(int hours, double rate); const double OVERTIME_RATE = 1.5; void main() { int hours; double rate, pay; … // more statements here cout << overtime << “ at “ << OVERTIME_RATE; } double calcGross(int hours, double rate) { if (hours > 40) return ( (40 * rate) + ((hours – 40) * rate * OVERTIME_RATE)); else return (hours * rate); }
Function Overloading • Same function name but different parameter types or number of parameters. • Function name along with parameter profile is referred to as the function signature. • Functions cannot be overloaded based on different modifiers or return type. • Function overloading is a form of polymorphism. • Polymorphism – Greek – many forms
double calcCost(double price, int quantity) { double subtotal; subtotal = quantity * price; return (subtotal); } //signature //calcCost( double, int); Function Overloading Example double calcCost(double price, double quantity) { double subtotal; subtotal = quantity * price; return (subtotal); } //signature //calcCost( double, double);
Summary • Top-Down Design • Black Box Analogy • Function Prototype • Function Call • Function Definition • Call-by-value • Variable Scope • Function Overloading