Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.

Similar presentations


Presentation on theme: "1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution."— Presentation transcript:

1 1 Chapter 7 Functions Dale/Weems/Headington

2 2 Functions l Control structures l every C++ program must have a function called main l program execution always begins with function main l any other functions are subprograms and must be called - can be called from anywhere and many times l when to use - easier to understand, maintain

3 3 Function Calls One function calls another by using the name of the called function next to ( ) enclosing an argument list. Program execution starts with first line of main A function call temporarily transfers control from the calling function to the called function. Function definitions - any order Compiler - one pass - translated in order Must be declared before used - physically precede function call

4 4 FunctionName ( Argument List ) The argument list is a way for functions to communicate with each other by passing information. The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function. Function Call Syntax

5 5 Two Parts of Function Definition int Cube ( int n ) heading { body return n * n * n ; }

6 6 What is in a heading? int Cube ( int n ) type of value returned name of function parameter list

7 7 What is in a prototype? A prototype looks like a heading but must end with a semicolon; and its parameter list just needs to contain the type of each parameter. It must be included if the main function is defined first int Cube( int ); // prototype

8 8 When a function is called, Definition usually appears after the main function call Temporary memory is set up ( for its value parameters and any local variables, and also for the function’s name if the return type is not void). Then the flow of control passes to the first statement in the function’s body. The called function’s body statements are executed until one of these occurs: return statement (with or without a return value), or, closing brace of function body. Then control goes back to where the function was called.

9 9 #include int Cube ( int ) ;// prototype using namespace std; void main ( ) { int yourNumber ; arguments int myNumber ; yourNumber = 14 ; myNumber = 9 ; cout << “My Number = “ << myNumber ; cout << “its cube is “ << Cube (myNumber) << endl ; cout << “Your Number = “ << yourNumber ; cout << “its cube is “ << Cube (yourNumber) << endl ; }

10 10 To Compile Successfully, l before a function is called in your program, the compiler must previously process either the function’s prototype, or the function’s definition (heading and body) l function prototype and definition must match - 2 separate functions l function definition - tells compiler the name, data type of return value and data types of parameters

11 11 A C++ function can return 2 TYPES l Value returning - in its identifier at most 1 value of the type which was specified (called the return type) in its heading and prototype - called part of an expression l void-function - cannot return any value in its identifier - complete stand-alone statement - parenthesis required

12 12 Writing void function l Void instead of int - no value returned l function definition - heading to } l no return l use an imperative word(s) - does something

13 13 Parameter/argument List l is the means used for a function to share information with the block containing the call - communicate with each other l different sets of data for different situations l can have different names than arguments l must match in number, type, position l commas separate multiple arguments

14 14 Classified by Location Always appear in a function call within the calling block. Always appear in the function heading, or function prototype. Arguments Parameters

15 15 Write a void function called DisplayMessage ( ) which you can call from main ( ) to describe the pollution index value it receives as a parameter. Your city describes a pollution Index less than 35 as “Pleasant”, 35 through 60 as “Unpleasant”, and above 60 as “Health Hazard.”

16 16 parameter void DisplayMessage( int index ) { if ( index < 35 ) cout << “Pleasant”; else if ( index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; }

17 17 #include void DisplayMessage (int); // prototype using namespace std; int main ( ) argument { int pollutionIndex; cout << “Enter air pollution index”; cin >> pollutionIndex; DisplayMessage(pollutionIndex); // call return 0; } The Rest of the Program

18 18 Variables l Local n Only accessible within block declared n cannot be shared - other functions n when called start over n when done - released l Global n while program is run n shared between functions

19 19 return; l is valid only in the body block of void functions l causes control to leave the function and immediately return to the calling block leaving any subsequent statements in the function body unexecuted l single-entry, single-exit

20 20 Header files contain declarations of l Contain function prototypes l named constants like const int INT_MAX = 32767; l function prototypes like float sqrt( float ); l classes like string, ostream, istream l objects like cin, cout

21 21 Parameters l Value parameters - receives a copy - change has no affect on argument - 2 separate copies n any type of argument allowed l Reference parameter - one copy - attach an & to type - changes argument n share same RAM spot n pass by address or pass by location n only variable argument allowed n data types must match - syntax error n same order - logic error

22 22 When to Use Reference Parameters l reference parameters should be used when you want your function to give a value to, or change the value of, a variable from the calling block without an assignment statement in the calling block

23 23 Questions l Why is a function used for a task? To cut down on the amount of detail in your main program (encapsulation). l Can one function call another function? Yes l Can a function even call itself? Yes, that is called recursion. It is very useful and requires special care in writing.

24 24 More Questions l Does it make any difference what names you use for parameters? NO. Just use them in function body. l Do parameter names and argument names have to be the same? NO. l What is the advantage of that? It seems confusing.

25 25 Functions are written to specifications l the specifications state the return type, the parameter types, whether any parameters are “outgoing,” and what task the function is to perform with its parameters l the advantage is that teamwork can occur without knowing what the argument identifiers (names) will be

26 26 Write prototype and function definition for l a void function called GetRating( ) with one reference parameter of type char l the function repeatedly prompts the user to enter a character at the keyboard until one of these has been entered: E, G, A, P to represent Excellent, Good, Average, Poor

27 27 void GetRating( char& ); // prototype void GetRating (char& letter) {cout << “Enter employee rating.” << endl; cout << “Use E, G, A, or P : ” ; cin >> letter; while ( (letter != ‘E’) && (letter != ‘G’) && (letter != ‘A’) && (letter != ‘P’) ) { cout << “Rating invalid. Enter again: ”; cin >> letter; }

28 28 #include void GetRating( char& ); // prototype using namespace std; int main( ) { char rating; rating = ‘X’; GetRating(rating);// call cout << “That was rating = “ << rating << endl; return 0; }

29 29 Designing a function l Design interface, design implementation l Hiding the code - not in main l Interface - specification of what it does and how it is called - outside world sees - what not how l Interface - precondition/postcondition

30 30 Designing a function l Implementation - supports the interface - satisfy postcondition with the precondition - algorithm l encapsulation - changes do not affect main l identifiers must match in number, type position l precondition must be true for function to work correctly l caller ensures precondition, called ensures postcondition

31 31 Documenting l The direction of the data flow - between the function and its caller l incoming - one way into function l outgoing - one way out of the function l incoming/outgoing - in and out of function

32 32 Data Flow Determines Passing-Mechanism Incoming /* in */ Pass-by-value Outgoing /* out */ Pass-by-reference Incoming/outgoing Pass-by-reference /* inout */ Parameter Data Flow Passing-Mechanism

33 33 An Assertion l is a truth-valued statement--one that is either true or false (not necessarily in C++ code) EXAMPLES studentCount > 0 sum is assigned && count > 0 response == ‘y’ or ‘n’ 0.0 <= deptSales <= 25000.0 beta == beta @ entry * 2

34 34 Preconditions and Postconditions l the precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked l the postcondition describes the state at the moment the function finishes executing l the caller is responsible for ensuring the precondition, and the function code must ensure the postcondition FOR EXAMPLE...

35 35 Function with Postconditions void GetRating ( /* out */ char& letter) // Precondition: None // Postcondition: User has been prompted to enter a character // && letter == one of these input values: E,G,A, or P { cout << “Enter employee rating.” << endl; cout << “Use E, G, A, or P : ” ; cin >> letter; while ( (letter != ‘E’) && (letter != ‘G’) && (letter != ‘A’) && (letter != ‘P’) ) { cout << “Rating invalid. Enter again: ”; cin >> letter; }

36 36 Function with Preconditions and Postconditions void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& root1, /* out */ float& root2 ) // Precondition: a, b, and c are assigned // && a != 0 && b*b - 4*a*c != 0 // Postcondition: root1 and root2 are assigned // && root1 and root2 are roots of quadratic with coefficients a, b, c { float temp; temp = b * b - 4.0 * a * c; root1 = (-b + sqrt(temp) ) / ( 2.0 * a ); root2 = (-b - sqrt(temp) ) / ( 2.0 * a ); return; }

37 37 Function with Preconditions and Postconditions void Swap( /* inout */ int& firstInt, /* inout */ int& secondInt ) // Precondition: firstInt and secondInt are assigned // Postcondition: firstInt == secondInt@entry // && secondInt == firstInt@entry { int temporaryInt ; temporaryInt = firstInt ; firstInt = secondInt ; secondInt = temporaryInt ; }

38 38 Assert library function l Executable assertions l header file l if true nothing happens, if false - execution of program terminates with error message l only convenient for developing program - never given to user

39 39 l Assign #14 - pg. 275-276, programming warm-up exercises 1, 3, 11; l Assign #15 - exam prep exercises 1, 2, 4, 5, 7, 8, 9, 10.


Download ppt "1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution."

Similar presentations


Ads by Google