1 / 22

CS102 Introduction to Computer Programming

CS102 Introduction to Computer Programming. Chapter 6 Functions Continued. Chapter 6 Topics. Storage Classes Static Local Variables Default Arguments Using Reference Variables as Parameters Inline Functions Overloaded Functions The exit() and atexit() Functions Stubs and drivers

Download Presentation

CS102 Introduction to Computer Programming

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. CS102Introduction to Computer Programming Chapter 6 Functions Continued

  2. Chapter 6 Topics • Storage Classes • Static Local Variables • Default Arguments • Using Reference Variables as Parameters • Inline Functions • Overloaded Functions • The exit() and atexit() Functions • Stubs and drivers • Testing Branches and Paths

  3. Storage Classes • Four types of storage classes Automatic Variables External Variables Register Variables Static Variables • All variables are assigned a default class • You can specify a variables storage class by placing the class name before its data type • This will affect the variables lifetime not its scope Concept - All variables belong to a storage class, which determines the period of time the variable exists in memory.

  4. Static Variables • Used to allow a local variable to remain in existence between function calls • makes the variable exist for the life time of the program • a static variable is only initialized once, when it is created • staticdata_type value; ex. static int Num; Concept - The variables stored in a functions local variables do not persist between function calls

  5. /* This program shows that local variables do not retain their values between function calls. */ #include <iostream.h> // Function prototype void ShowLocal(void); void main(void) { ShowLocal(); ShowLocal(); } /* Definition of function ShowLocal. The initial value of LocalNum, which is 5, is displayed. The value of LocalNum is then changed to 99 before the function returns. */  void ShowLocal(void) { int LocalNum = 5; // Local variable cout << "LocalNum is " << LocalNum << endl; LocalNum = 99; } Program 6-20 Program Output LocalNum is 5 LocalNum is 5

  6. /* This program uses a static local variable */ #include <iostream.h> // Function prototype void ShowStatic(void); void main(void) { for (int Count = 0; Count < 5; Count++) ShowStatic(); } // Definition of function ShowStatic. void ShowStatic(void) { static int StatNum = 0; cout << "StatNum is " << StatNum << endl; StatNum++; } StatNum is 0 Program 6-21 This program demonstrates the effect of defining a variable as static Program Output StatNum is 1 StatNum is 2 StatNum is 3 StatNum is 4

  7. Default Arguments • The value of a default argument must be a constant (a literal value or a named constant) • When an argument is left out of a function call, all the arguments that come after it must be left out as well. • If a function has a mixture of parameters, the parameters with default arguments must be declared last. Concept - Default arguments are passed to parameters automatically if no argument is provided in the function call.

  8. Defining Default Arguments • In the function prototype void showArea (float = 20, float = 10); void showArea (float length = 20, float width = 10); • In the function definition void showArea (float length = 20, float width = 10) float area = length * width; cout << “the area is “ << area << endl: Concept – If there is not function prototype the default arguments can be placed in the function definition

  9. /* This program demonstrates default function arguments. */ #include <iostream.h> // Function prototype with default arguments */ void DisplayStars(int = 10, int = 1); void main(void) { DisplayStars(); cout << endl; DisplayStars(5); cout << endl; DisplayStars(7, 3); } /* Definition of function DisplayStars. The default argument for Cols is 10 and for Rows is 1. This function displays a rectangle made of asterisks. */ void DisplayStars(int Cols, int Rows) { /* Nested loop. The outer loop controls the rows and the inner loop controls the columns. */ for (int Down = 0; Down < Rows; Down++) { for (int Across = 0; Across < Cols; Across++) cout << "*"; cout << endl; } } Program 6-23 Program Output ********** ***** ******* ******* *******

  10. Using Reference Variables as Parameters • A reference variable is an alias to another variable. • Reference variables are declared with an & in front of the variable name data_type &variable_name; ex. int &Num; • Reference variables in function prototype statements, include the & after the data type return_typefunction-name( data_type & ); ex. Void func ( int & ); Concept - Reference variables allow a function to access the parameters original argument and apply changes to it.

  11. /* This program uses a reference variable as a function parameter. */ #include <iostream.h> /* Function prototype. The parameter is a reference variable. */ void DoubleNum(int &); void main(void) { int Value = 4; cout << "In main, Value is " << Value << endl; cout << "Now calling DoubleNum..." << endl; DoubleNum(Value); cout << "Now back in main. Value is " << Value << endl; } /* Definition of DoubleNum. The parameter RefVar is a reference variable. The value in RefVar is doubled. */ void DoubleNum (int &RefVar) { RefVar *= 2; } Program 6-24 Reference Variable Program Output In main, Value is 4 Now calling DoubleNum... Now back in main. Value is 8

  12. /* This program uses reference variables as function parameters*/ #include <iostream.h> /* Function prototypes. Both functions use reference variables as parameters*/ void DoubleNum(int &); void GetNum(int &); void main(void) { int Value; GetNum(Value); DoubleNum(Value); cout << "That value doubled is " << Value << endl; } /* Definition of GetNum. The parameter UserNum is a reference variable. The user is asked to enter a number, which is stored in UserNum. */ void GetNum(int &UserNum) { cout << "Enter a number: "; cin >> UserNum; } /* Definition of DoubleNum. The parameter RefVar is a reference variable. The value in RefVar is doubled. */ void DoubleNum (int &RefVar) { RefVar *= 2; } Program 6-25 Program Output Enter a number: 12 [Enter] That value doubled is 24

  13. Reference Argument Warning • Don’t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable that’s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them.

  14. Overloaded Functions • C++ uses both the function name and the parameter list to determine which function is being called. • C++ will match the argument list of the function call with the parameter list of the functions defined and find a unique match. Concept - Two or more functions may have the same name as long as their parameter lists are different.

  15. /* This program uses overloaded functions */ #include <iostream.h> // Function prototypes int Square(int); float Square(float); void main(void) { int UserInt; float UserFloat; cout.precision(2); cout << "Enter an integer and a floating-point value: "; cin >> UserInt >> UserFloat; cout << "Here are their squares: "; cout << Square(UserInt) << " and " << Square(UserFloat); } */ Definition of overloaded function Square. This function uses an int parameter, Number. It returns the square of Number as an int. */ int Square(int Number) { return Number * Number; } /* Definition of overloaded function Square. This function uses a float parameter, Number. It returns the square of Number as a float.*/ float Square(float Number) { return Number * Number; } Program 6-26 Program Output Enter an integer and floating-point value: 12 4.2 [Enter] Here are their squares: 144 and 17.64

  16. The exit and atexit Functions • Must #include stdlib.h to use exit() and atexit function • exit returns and integer: ex. exit(0); • this value is returned to the operating system that your program is running within. • EXIT_FAILURE and EXIT_SUCCESS • atexit registers a function to be called when the exit function is executed: ex. atexit(stop); Concept - exit and atexit provides a mechanism for terminating a program while executing in a function.

  17. /* This program shows how the exit function causes a program to stop executing.*/ #include <iostream.h> #include <stdlib.h> // For exit void Function(void); // Function prototype void main(void) { Function(); } /* This function simply demonstrates that exit can be used to terminate a program from a function other than main. */ void Function(void) { cout << "This program terminates with the exit function.\n"; cout << "Bye!\n"; exit(0); cout << "This message will never be displayed\n"; cout << "because the program has already terminated.\n"; } Program 6-30 Program Output This program terminates with the exit function. Bye!

  18. /* This program demonstrates the exit function. */ #include <iostream.h> #include <stdlib.h> // For exit #include <ctype.h> // For toupper void main(void) { char Response; cout << "This program terminates with the exit function.\n"; cout << "Enter S to terminate with the EXIT_SUCCESS code\n"; cout << "or F to terminate with the EXIT_FAILURE code: "; cin >> Response; switch (Response) {case 's' : case 'S' :cout << "Exiting with EXIT_SUCCESS.\n"; exit(EXIT_SUCCESS); case 'f' : case 'F' : cout << "Exiting with EXIT_FAILURE.\n"; exit(EXIT_FAILURE);} } Program 6-31 Program Output This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or F to terminate with the EXIT_FAILURE code: s [Enter] Exiting with EXIT_SUCCESS. Program Output This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or F to terminate with the EXIT_FAILURE code: f [Enter] Exiting with EXIT_FAILURE.

  19. Stubs and Drivers • A stub is a dummy function that can be quickly implemented and called in place of the real function • A driver is program that tests a function by calling it with a range of test data passed in as arguments. Concept – Stubs and Drivers are very helpful tools for testing and debugging programs that use functions

  20. Stubs • Functionally decompose your program into individual algorithms and subroutines • Write Stubs that allow your top level functions to continue executing • return static or typical values • Display debug messages • Simply return without doing anything • Replace the stubs with the real functions when you have completed debugging the top level functions Concept – Stubs allow you to focus on the logical flow of a program with out having to write all the code.

  21. Switch (choice) { case 1 : Adult (months); break; case 2 : Child (months); break; case 3 : Senior (months); break; case 4 : exit(0); break; default: cout <<"Enter a number"; cout <<" between 1 - 4"; } void Adult (int period) { cout << “You have called the Adult function”; } void Adult (int period) { cout << “You have called the Child function”; } void Adult (int period) { cout << “You have called the Senior function”; } Stubs for Menu Calls

  22. Drivers • Develop the function based on the written specification • Write a program that calls the function with various arguments as inputs • In range • Out of range • Exercise each path or branch • Use the calling program to display the results Concept – Drivers allow you to develop functions independent of the calling functions

More Related