writing functions
play

Writing Functions Chapter 9 1 2 Reminder Why Functions? Better - PDF document

3/16/2009 For Next Time Read Chapter 9 Writing Functions Chapter 9 1 2 Reminder Why Functions? Better manage the complexity of larger Test #2 is Wednesday, March 18 programs Thats one week from today! Reuse the same


  1. 3/16/2009 For Next Time  Read Chapter 9 Writing Functions Chapter 9 1 2 Reminder Why Functions?  Better manage the complexity of larger  Test #2 is Wednesday, March 18 programs  That’s one week from today!  Reuse the same code from multiple places  Emphasizes Chapters 5 – 10 within a program  Conditional statements ( if/else , switch )  Encapsulate functionality into ―black boxes‖  Loops ( while , do/while , for )  Programmer focus on smaller, easier  Calling and writing functions subproblems solved in isolation  Call by value vs. call by reference  Recursion, pointers, etc. Definition vs. Invocation Function Definition  Definition — provides the code that determines the function’s behavior  Type type name ( parameters )  Invocation — is the execution of the function  Name { by client code  Formal body void count(int n) Parameters } { for ( int i = 0; i < n; i++ ) count(5);  Body cout << i << endl; } 1

  2. 3/16/2009 Function Type Function Name  Type can be any  An identifier C++ type plus type name ( parameters ) type name ( parameters ) void  Should accurately describe the purpose  The void type { { of the function body means the body } function does not } return a value to the client Function Parameters Function Parameters  Comma-  List of statements type name ( parameters ) separated the function is to { type name ( parameters ) list of execute body parameter {  May declare its own } body declarations local variables }  May be empty Function Parameters Call by Value  Actual parameters are assigned to the formal  Formal parameters parameters when the client calls the function  Parameters in the function definition  This assignment is performed automatically and  Actual parameters does not appear in your code  Parameters (or arguments) provided by the  Since the function works on copies of the client actual parameters, the function cannot  May be variables, literal values, constants, directly affect the actual parameters and expressions  A variable local to the client may be modified via the function’s return type 2

  3. 3/16/2009 Local Variables Function Documentation  Variables declared within a function are local  Essential information to that function  Purpose  Local variables are not visible to code outside  Role of each parameter that function definition  Nature of return value  The name of a local variable can be the same  Other helpful information as the name of a local variable in another  Author function — they are different variables  Date  Formal parameters are local to function  References definitions Next . . . More on functions 15 3

Recommend


More recommend