1 / 71

CHAPTER 7 USER-DEFINED FUNCTIONS II

CHAPTER 7 USER-DEFINED FUNCTIONS II. VOID FUNCTIONS Void functions and value-returning functions have similar structures. Both have a heading part and a statement part. User-defined void functions can be placed either before or after the function main .

susanna
Télécharger la présentation

CHAPTER 7 USER-DEFINED FUNCTIONS II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 7USER-DEFINED FUNCTIONS II

  2. VOID FUNCTIONS • Void functions and value-returning functions have similar structures. • Both have a heading part and a statement part. • User-defined void functions can be placed either before or after the function main. • The program execution always begins with the first statement in the function main. • If you place user-defined void functions after the function main, you should place the function prototype before the function main. • A void function does not have a data type and so functionType in the heading part and the return statement in the body of the void function are meaningless. • In a void function, you can use the return statement without any value; it is typically used to exit the function early. • Void functions may or may not have formal parameters. • A call to a void function is a stand-alone statement.

  3. Void Functions without Parameters Syntax Function Definition void functionName(void) { statements } The word void inside the parentheses is optional. • In C++,void is a reserved word. Syntax Function Call functionName();

  4. Example 7-1 ****************************** ****************************** ********** Annual *********** ****************************** ****************************** ******* Spring Sale ********** ****************************** ******************************

  5. #include <iostream> using namespace std; void printStars(void); int main() { printStars(); //Line 1 cout<<"********** Annual ***********"<<endl; //Line 2 printStars(); //Line 3 cout<<"******* Spring Sale **********"<<endl; //Line 4 printStars(); //Line 5 return 0; } void printStars(void) { cout<<"******************************"<<endl; cout<<"******************************"<<endl; }

  6. Void Functions with Parameters Syntax Function Definition void functionName(formal parameter list) { statements } Syntax Formal parameter list: dataType& variable, dataType& variable, ...

  7. Syntax Function Call functionName(actual parameter list); Syntax Actual Parameter List expression or variable, expression or variable, …

  8. Sample Run: The user input is in red. Enter the number of star lines (1 to 20) to be printed--> 15 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

  9. Example 7-4 //Program: Print a triangle of stars #include <iostream> using namespace std; void printStars(int blanks, int starsInLine); int main() { int numberOfLines; int counter; int numberOfBlanks; cout<<"Enter the number of star lines (1 to 20)" <<" to be printed--> "; //Line 1 cin>>numberOfLines; //Line 2

  10. while(numberOfLines < 0 || numberOfLines > 20) //Line 3 { cout<<"Number of star lines should be " <<"between 1 and 20"<<endl; //Line 4 cout<<"Enter the number of star lines " <<"(1 to 20)to be printed--> "; //Line 5 cin>>numberOfLines; //Line 6 } cout<<endl<<endl; //Line 7 numberOfBlanks = 30; //Line 8 for(counter = 1; counter <= numberOfLines; counter++) //Line 9 { printStars(numberOfBlanks, counter); //Line 10 numberOfBlanks--; //Line 11 }

  11. return 0; //Line 12 } void printStars(int blanks, int starsInLine) { int count; for(count = 1; count <= blanks; count++) //Line 13 cout<<" "; //Line 14 for(count = 1; count <= starsInLine; count++) //Line 15 cout<<" *"; //Line 16 cout<<endl; }

  12. Value Parameter: A formal parameter that receives a copy of the content of the corresponding actual parameter. • Reference Parameter:A formal parameter that receives the location (memory address) of the corresponding actual parameter. • When we attach & after the dataType in the formal parameter list of a function, then the variable following that dataType becomes a reference parameter. Example 7-3 void expfun(int one, int& two, char three, double& four);

  13. If a formal parameter is a value parameter, the value of the corresponding actual parameter is copied into the formal parameter. • The value parameter has its own copy of the data. • During program execution, the value parameter manipulates the data stored in its own memory space. • If a formal parameter is a reference parameter, it receives the address of the corresponding actual parameter. • A reference parameter stores the address of the corresponding actual parameter. • During program execution to manipulate the data, the address stored in the reference parameter directs it to the memory space of the corresponding actual parameter.

  14. Reference Parameters • Value parameters provide only a one-way link between actual parameters and formal parameters. • A reference parameter receives the address of the actual parameter. • Reference parameters can pass one or more values from a function and can change the value of the actual parameter. • Reference parameters are useful in three situations: • When you want to return more than one value from a function • When the value of the actual parameter needs to be changed • When passing the address would save memory space and time relative to copying a large amount of data

  15. Example 7-5 Given the course score (a value between 0 and 100), the following program determines the course grade of a student. 1. main a. Get Course Score. b. Print Course Grade. 2. getScore a. Prompt the user for the input. b. Get the input. c. Print course score. 3. printGrade a. Calculate the course grade. b. Print course grade.

  16. // Program: Compute grade. // This program reads a course score and prints the // associated course grade. #include <iostream> using namespace std; void getScore(int& score); void printGrade(int score); int main () { int courseScore; cout<<"Line 1: Based on the course score, this program " <<"computes the course grade."<<endl; //Line 1

  17. getScore(courseScore); //Line 2 printGrade(courseScore); //Line 3 return 0; } void getScore(int& score) { cout<<"Line 4: Enter course score--> "; //Line 4 cin>>score; //Line 5 cout<<endl<<"Line 6: Course score is " <<score<<endl; //Line 6 }

  18. void printGrade(int score) { cout<<"Line 7: Your grade for the course is "; //Line 7 if(score >= 90) //Line 8 cout<<"A"<<endl; else if(score >= 80) cout<<"B"<<endl; else if(score >= 70) cout<<"C"<<endl; else if(score >= 60) cout<<"D"<<endl; else cout<<"F"<<endl; }

  19. Sample Run: Line 1: Based on the course score, this program computes the course grade. Line 4: Enter course score--> 85 Line 6: Course score is 85 Line 7: Your grade for the course is B

  20. VALUE AND REFERENCE PARAMETERS AND MEMORY ALLOCATION • When a function is called, memory for its formal parameters and variables declared in the body of the function (called local variables) is allocated in the function data area. • In the case of a value parameter, the value of the actual parameter is copied into the memory cell of its corresponding formal parameter. • In the case of a reference parameter, the address of the actual parameter passes to the formal parameter. • Content of the formal parameter is an address. • During execution, changes made by the formal parameter permanently change the value of the actual parameter. • Stream variables (for example, ifstream and ofstream) should be passed by reference to a function.

  21. Example 7-6 //Example 7-6: Reference and value parameters #include <iostream> using namespace std; void funOne(int a, int& b, char v); void funTwo(int& x, int y, char& w); int main() { int num1, num2; char ch; num1 = 10; //Line 1 num2 = 15; //Line 2 ch = 'A'; //Line 3

  22. cout<<"Line 4: Inside main: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line 4 funOne(num1, num2, ch); //Line 5 cout<<"Line 6: After funOne: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line 6 funTwo(num2, 25, ch); //Line 7 cout<<"Line 8: After funTwo: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line return 0; }

  23. void funOne(int a, int& b, char v) { int one; one = a; //Line 9 a++; //Line 10 b = b * 2; //Line 11 v = 'B'; //Line 12 cout<<"Line 13: Inside funOne: a = "<<a<<", b = "<<b <<", v = "<<v<<", and one = "<<one<<endl;//Line 13 } void funTwo(int& x, int y, char& w) { x++; //Line 14 y = y * 2; //Line 15 w = 'G'; //Line 16 cout<<"Line 17: Inside funTwo: x = "<<x <<", y = "<<y <<", and w = "<<w<<endl;//Line 17 }

  24. Output: Line 4: Inside main: num1 = 10, num2 = 15, and ch = A Line 13: Inside funOne: a = 11, b = 30, v = B, and one = 10 Line 6: After funOne: num1 = 10, num2 = 30, and ch = A Line 17: Inside funTwo: x = 31, y = 50, and w = G Line 8: After funTwo: num1 = 10, num2 = 31, and ch = G

  25. Just before Line 1 executes, memory is allocated only for the variables of the function main; this memory is not initialized. After Line 3 executes, the variables are as shown in Figure 7-1.

  26. cout<<"Line 4: Inside main: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line 4 Line 4 produces the following output. Line 4: Inside main: num1 = 10, num2 = 15, and ch = A

  27. one = a; //Line 9 Just before Line 9 executes, the variables are as shown in Figure 7-2.

  28. one = a; //Line 9 After Line 9 (one = a;)executes, the variables are as shown in Figure 7-3.

  29. a++; //Line 10 After Line 10 (a++;) executes, the variables are as shown in Figure 7-4.

  30. b = b * 2; //Line 11 After Line 11 (b = b * 2;) executes, the variables are as shown in Figure 7-5.

  31. v = 'B'; //Line 12 After Line 12 (v = 'B';) executes, the variables are as shown in Figure 7-6.

  32. cout<<"Line 13: Inside funOne: a = "<<a<<", b = "<<b <<", v = "<<v<<", and one = "<<one<<endl;//Line 13 Line 13 produces the following output. Line 13: Inside funOne : a = 11, b = 30, v = B, and one = 10

  33. After the execution of line 13, control goes back to line 6 and memory allocated for the variables of function funOne is deallocated. Figure 7-7 shows the values of the variables of the function main.

  34. cout<<"Line 6: After funOne: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line 6 Line 6 produces the following output. Line 6: After funOne : num1 = 10, num2 = 30, and ch = A

  35. x++; //Line 14 Before the execution of Line 14.

  36. x++; //Line 14 After Line 14 (x++;) executes, the variables are as shown in Figure 7-9.

  37. y = y * 2; //Line 15 After Line 15 (y = y * 2;)executes, the variables are as shown in Figure 7-10.

  38. w = 'G'; //Line 16 After Line 16 (w = 'G';) executes, the variables are as shown in Figure 7-11.

  39. cout<<"Line 17: Inside funTwo: x = "<<x <<", y = "<<y <<", and w = "<<w<<endl;//Line 17 Line 17 produces the following output. Line 17: Inside funTwo : x = 31, y = 50, and w = G

  40. After the execution of Line 17, control goes to Line 8. The memory allocated for the variables of function funTwo is deallocated.

  41. cout<<"Line 8: After funTwo: num1 = "<<num1 <<", num2 = "<<num2<<", and ch = "<<ch<<endl; //Line 8 Line 8 produces the following output. Line 8: After funTwo : num1 = 10, num2 = 31, and ch = G After the execution of line 8, the program terminates.

  42. REFERENCE PARAMETERS AND VALUE-RETURNING FUNCTIONS • SCOPE OF AN IDENTIFIER • The scope of an identifier refers to where in the program an identifier is accessible (that is visible). • Local identifier: Identifiers declared within a function (or block). • Global identifier: Identifiers declared outside of every function definition. • C++ does not allow the nesting of functions. That is, the definition of one function cannot be included in the body of another function.

  43. 1. Global identifiers (such as variables) are accessible by a function or a block if, a. The identifier is declared before the function definition (block), b. The function name is different from the identifier, c. All parameters of the function have names different than the name of the identifier, d. All local identifiers (such as local variables) have names different than the name of the identifier. 2. (Nested Block) An identifier declared within a block is accessible a. Only within the block from the point they are declared until the end of the block and b. By those blocks that are nested within that block if the nested block does not have an identifier with the same name as that of the outside block (the block that encloses the nested block.) 3. The scope of a function name is similar to the scope of an identifier declared outside of any block.

  44. C++ allows the programmer to declare a variable in the initialization statement of the for statement. for(int count = 1; count < 10; count++) cout<<count<<endl; • The scope of the variable count is limited to only the body of the for loop.

  45. #include <iostream> using namespace std; constdouble rate = 10.50; int z; double t; void one(int x, char y); void two(int a, int b, char x); void three(int one, double y, int z); int main () { int num, first; double x, y, z; char name, last; . . . return 0; }

  46. void one(int x, char y) { . . . } int w; void two(int a, int b, char x) { int count; . . . }

  47. void three(int one, double y, int z) { char ch; int a; . . . //Block four { int x; char a; . . }//end Block four . . . }

  48. 1. Some compilers initialize global variables to their default values. 2. In C++, :: is called the scope resolution operator.By using the scope resolution operator, a global variable declared before the definition of a function (block) can be accessed by the function (or block) even if the function (or block) has an identifier with the same name as the variable. 3. C++ provides a way to access a global variable declared after the definition of a function. In this case, the function must not contain any identifier with the same name as the global variable. In the preceding example, the function one does not contain any identifier named w. Therefore, w can be accessed by function one if you declare w as an externalvariable inside one. To declare w as an external variable inside function one, the function one must contain the following statement: externint w;

  49. SIDE EFFECTS OF GLOBAL VARIABLES • Using global variables has side effects. • Any function that uses global variables is not independent and usually it cannot be used in more than one program. • Also, if more than one function uses the same global variable and if something goes wrong, it is difficult to find what went wrong and where. • Problems caused by global variables in one area of a program might be misunderstood as problems caused in another area. • Use appropriate parameters instead of using global variables.

More Related