MORE ON MODULAR DESIGN MODULE COMMUNICATIONS by khn19658

VIEWS: 4 PAGES: 58

									    MORE ON MODULAR
     DESIGN: MODULE
    COMMUNICATIONS


1
    WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED
    LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE
    OF EACH ACTUAL PARAMETER IS COPIED INTO THE
    CORRESPONDING LOCAL MEMORY CELL. THIS IS
    REFERRED TO AS PASS BY COPY (VALUE).
    BECAUSE THE MODULE DOES NOT KNOW THE LOCATION
    OF THE ACTUAL PARAMETER, IT CAN MANIPULATE THIS
    LOCAL COPY, BUT IT CAN NOT CHANGE ITS CONTENT.




2
    ANOTHER METHOD OF PASSING PARAMETERS IS
    REFERRING TO MEMORY LOCATIONS BEYOND THE
    FUNCTION. IN SUCH CASE, THERE IS ONLY ONE MEMORY
    LOCATION FOR THE DATA, WHICH IS USED BY THE
    CALLING MODULE AND THE MODULE BEING CALLED. ANY
    CHANGE THAT A MODULE MAKES TO ITS FORMAL
    PARAMETERS AFFECTS THE ACTUAL PARAMETERS.




3
        RETURN PARAMETERS

    THE FUNCTION MAY RETURN A SINGLE VALUE USING A
    return STATEMENT.
    HOWEVER, MORE THAN ONE RESULT MAY BE RETURNED
    TO THE CALLING MODULE USING PARAMETERS.




4
PROGRAM FindAvg (REVISITED)
// FILE: FindAvg2.cpp
// Finds the average of three test scores
#include <iostream.h>
// global data:
float test1, test2, test3, average;

void main ()
{
  // functions used:
  void Get_data ();
  void Find_average ();
  void Display_results ();
  // function calls:
  Get_data ();
  Find_average ();
  Display_results ();
  return;
}
5
    FUNCTION Find_average
    .
    .
    void Find_average()
    {
      // Calculates the average
      const int NUMBER_OF_TESTS = 3;
      average = (test1 + test2 + test3) / NUMBER_OF_TESTS;
      return;
    } // end Find_average()
    .
    .


THE VALUE OF average IS RETURNED TO THE CALLING
MODULE BY WAY OF GLOBAL VARIABLE.


6
    FUNCTION Find_average
     RECODED TO RETURN
      total AND average
// FILE: FindTotAvg.cpp
// Finds the total and average of three numbers

:
void Find_tot_avg
  (float num1, float num2, float num3,
                                // IN: 3 values
   float &total,                // OUT: total of the values
   float &average)              // OUT: average of the values
{
  // Calculates total and average
  const int NUMBER_OF_VALUES = 3;
  total = num1 + num2 + num3;
  average = total / NUMBER_OF_VALUES;
  return;
} // end Find_tot_avg()
7
        THE FUNCTION CALL

    Find_tot_avg (test1, test2, test3, total, average);




8
    THE FUNCTION PROTOTYPE

// Finds the total and average of three test scores

void Find_tot_avg
  (float, float, float,         // IN: values for 3 tests
   float &,                     // OUT: total of test scores
   float &);                    // OUT: average of test scores




9
         PARAMETER
       CORRESPONDENCE
     ACTUAL PARAMETERS   FORMAL PARAMETERS

         test1                 num1
         test2                 num2
         test3                 num3
         total                 total
         average               average




10
          STATE OF MEMORY
            ALLOCATION
               (BEFORE EXECUTION OF FUNCTION)


                 test1   85.0      85.0      num1



                 test2   90.0      90.0      num2

 ACTUAL                                                     FORMAL
 PARAMETERS                                                 PARAMETERS
                 test3   80.0      80.0      num3



                total    ?        address           total
                                  of total


              average             address           average
                         ?        of average
11
              STATE OF MEMORY
                ALLOCATION
                (AFTER EXECUTION OF FUNCTION)


                 test1    85.0      85.0      num1



                 test2    90.0      90.0      num2

 ACTUAL                                                      FORMAL
 PARAMETERS                                                  PARAMETERS
                 test3    80.0      80.0      num3



                total              address
                         255.0     of total          total



              average              address
                         85.0      of average        average
12
       PARAMETER CATEGORIES

     PARAMETERS ARE PASSED IN EITHER OF TWO WAYS:

      1. BY VALUE
      2. BY REFERENCE




13
     IN CASE OF THE VALUE ITSELF BEING PASSED,
       ONLY A COPY OF WHAT IS STORED ON THE
     MEMORY, AND NOT THE LOCATION, IS SHARED. A
       SEPARATE MEMORY CELL IS ALLOCATED TO
          HOLD THE CORRESPONDING FORMAL
                    PARAMETERS.




14
      WITH REFERENCE PARAMETERS (DENOTED WITH THE &
      SYMBOL FOLLOWING THE TYPE OF THE FORMAL PARAMETER),

     THERE IS ONLY ONE MEMORY LOCATION FOR THE DATA,
      WHICH IS USED BY THE CALLING MODULE AND THE
     MODULE BEING CALLED. ANY CHANGE THAT A MODULE
      MAKES TO ITS FORMAL PARAMETERS AFFECTS THE
                    ACTUAL PARAMETERS.



15
     DATA FLOW DESIGN
       FOR MODULES
CAN BE CATEGORIZED INTO THREE TYPES:

1. DATA IMPORT: WHAT THE CALLING MODULE HAS THAT
   THE CALLED MODULE NEEDS.

2. DATA EXPORT: WHAT THE CALLED MODULE
   COMPUTES AND RETURNS TO THE CALLING MODULE.

3. DATA IMPORT/ EXPORT: WHAT THE CALLING MODULE
   HAS THAT THE CALLED MODULE NEEDS, CHANGES,
   AND RETURNS TO THE CALLING MODULE.

16
     ANY OBJECT THAT CAN BE CLASSIFIED AS IMPORT

              SHOULD BE PASSED BY VALUE.


       ITEMS IN THE REMAINING TWO CATEGORIES

      (EXPORT AND IMPORT/EXPORT) MUST BE PASSED

                    BY REFERENCE.




17
      SUGGESTED GUIDELINES
     FOR PARAMETER PASSING
                       (VALUE)
     WHEN DATA IS PASSED TO A FUNCTION AND IS NOT TO BE
     CHANGED, THEN FORMAL PARAMETER SHOULD BE A VALUE
     PARAMETER.
     WHEN DATA IS PASSED TO A FUNCTION AND IS CHANGED,
     BUT THE CHANGE IS NOT TO AFFECT THE VALUE OUTSIDE
     THE FUNCTION, THEN THE FORMAL PARAMETER SHOULD BE
     A VALUE PARAMETER.


18
      SUGGESTED GUIDELINES
     FOR PARAMETER PASSING
                    (REFERENCE)

     WHEN DATA IS PASSED TO A FUNCTION AND IS CHANGED AND
     IS TO BE RETURNED, THEN FORMAL PARAMETER SHOULD BE
     A REFERENCE PARAMETER.
     WHEN INFORMATION IS GENERATED IN A FUNCTION AND IS TO
     BE RETURNED, THEN THE FORMAL PARAMETER SHOULD BE
     A REFERENCE PARAMETER.



19
     ADDITIONAL REASONS
          FOR USING
      VALUE PARAMETERS

     1. TO MAKE THE DATA FLOW DESIGN CLEAR.

     2. TO PREVENT UNWANTED SIDE EFFECTS

     3. TO HAVE ACTUAL PARAMETERS AS CONSTANTS
        OR EXPRESSIONS (IF NEEDED).


20
     EXPRESSIONS AS ACTUAL
          PARAMETERS


     Find_tot_avg (test1 + extra_credit_1,
                   test2 + extra_credit_2,
                   test3 + extra_credit_3, total, average);




21
     ADDITIONAL REASONS FOR
        USING REFERENCE
           PARAMETERS
     1. MULTIPLE RESULTS RETURNED FROM MODULES CAN
        ONLY BE PASSED BACK THROUGH REFERENCE
        PARAMETERS.

     2. MORE EFFICIENT MEMORY MANAGEMENT.



22
               PARAMETER
             CORRESPONDENCE
     THE CORRESPONDENCE BETWEEN ACTUAL AND FORMAL
     PARAMETERS IS DETERMINED BY THE POSITION. ALSO,
     THERE SHOULD BE CONSISTENCY WITH RESPECT TO THE
     PARAMETER TYPE.




23
      TYPE CONVERSION
     ALTHOUGH IDENTICAL MATCH BETWEEN ACTUAL AND
     FORMAL PARAMETER TYPE IS DESIRABLE, IN THE CASE
     OF MISMATCH, THE COMPILER MAY PERFORM A
     CONVERSION (THE RESULT PRODUCED MAY NOT BE THE
     DESIRED ONE).

     WHEN NECESSARY, EXPLICIT CONVERSION USING
     CASTING OPERATORS SHOULD BE USED.




24
                         EXAMPLE:



     IF total_grade IS A float VARIABLE, THE EXPRESSION
     int (total_grade)

     CREATES A COPY OF total_grade OF TYPE int.



     float MAY BE USED TO CREATE A FLOATING POINT COPY
     OF AN int VALUE.



25
     SCOPE OF OBJECTS
 A TRANSLATION-TIME CONCERN. DETERMINES WHERE
   IN A PROGRAM A GIVEN OBJECT MAY BE ACCESSED.



      THE FOUR SCOPES FOR AN OBJECT ARE:

     1. FILE SCOPE

     2. FUNCTION SCOPE

     3. BLOCK SCOPE

     4. FUNCTION-PROTOTYPE SCOPE
26
          SCOPE RULES:
               FILE SCOPE
     AN OBJECT DECLARED OUTSIDE ANY FUNCTION IS
     ACCESSIBLE FROM ALL FUNCTIONS THAT FOLLOW ITS
     DECLARATION.
     GLOBAL VARIABLES, CLASSES, FUNCTION DEFINITIONS,
     AND FUNCTION PROTOTYPES PLACED OUTSIDE A
     FUNCTION ALL HAVE FILE SCOPE.




27
          SCOPE RULES:
           FUNCTION SCOPE
     LABELS (i.e. case LABELS IN switch STATEMENT)
     ARE THE ONLY OBJECTS WITH FUNCTION SCOPE.
     LABELS CAN BE REFERENCED ONLY IN THE
     FUNCTION IN WHICH THEY APPEAR.




28
           SCOPE RULES:
              BLOCK SCOPE
     AN OBECT DECLARED INSIDE A BLOCK IS ACCESSIBLE
     FROM ITS DECLARATION TO THE END OF THE BLOCK
     (THE RIGHT BRACE “}”).
     LOCAL VARIABLES AND FUNCTION PARAMETERS HAVE
     BLOCK SCOPE.




29
          SCOPE RULES:
        FUNCTION-PROTOTYPE
               SCOPE
     OBJECTS USED IN THE PARAMETER LIST OF A
     FUNCTION PROTOTYPE (NOT REQUIRED) HAVE
     FUNCTION-PROTOTYPE SCOPE. THOSE OBJECTS CAN
     BE REUSED ELSEWHERE IN THE PROGRAM.




30
       NAMING CONFLICTS

     ANY BLOCK MAY CONTAIN OBJECT DECLARATIONS.
     WHEN BLOCKS ARE NESTED, AND THE SAME OBJECT
     NAME IS INCLUDED IN MORE THAN ONE BLOCK,
     ACCESS IS GIVEN TO THE OBJECT WITHIN THE BLOCK
     THAT IS CURRENTLY IN EXECUTION.




31
                      EXAMPLE:
// FILE: SimpleScope.cpp
#include <iostream.h>
     float a, b, c;
     int d;
void main ()
{
  void Average (float, float, float, int &);
  cin >> a >> b >> c;
  Average (a, b, c, d);
  cout << d << endl;
  return;
} // end of main ()
void Average (float x, float y, float z, int &w)
{
  float total;
  total = x + y + z;
  w = total / 3; // result is automatically converted to int
  return;
} // end of Average ()

32
     ANOTHER EXAMPLE:
     // FILE: NestedScope.cpp

     float number;

     void main ()
     {
       :
     } // end of main ()

     void Module_one ()
     {
       float total;
         :
     } // end of Module_one ()

     float Module_two ()
     {
       float total;

        :
        {
            int sum;
               :
            sum = sum + total;
        }
        :
     } // end of Module_two ()

33
             SIDE EFFECTS
     ANY EFFECT OF ONE MODULE ON ANOTHER MODULE

       THAT IS NOT A PART OF THE EXPLICITLY DEFINED

                DATA FLOW BETWEEN THEM.



     WHEN A MODULE ACCESSES INFORMATION OUTSIDE

        OF ITS OWN BLOCK IN A MANNER OTHER THAN

        THROUGH ITS PARAMETERS, THE POTENTIAL

           EXISTS FOR UNWANTED SIDE EFFECTS.

34
     IT IS ALSO POSSIBLE FOR UNWANTED SIDE EFFECTS

     TO OCCUR IF A FORMAL REFERENCE PARAMETER IS

     USED WHERE A VALUE PARAMETER WILL SUFFICE.




35
     AVOIDING SIDE EFFECTS
     MODULES SHOULD ACCESS NONLOCAL VARIABLES

     THROUGH THEIR PARAMETER LISTS AND FUNCTION

      RESULTS, AND ALL IMPORTS ONLY PARAMETERS

        SHOULD BE PASSED AS VALUE PARAMETERS.




36
                       REFERENCE
                       PARAMETERS


                  MAIN PROGRAM
                    (OR OTHER
                 CALLING MODULE)

NON-PARAMETER            VALUE
 RELATIONSHIP          PARAMETERS


                      CALLED
                      MODULE
                                        FUNCTION
                                         RESULT

37
                AVOIDING SIDE EFFECTS
                  EXAMPLE:



// FILE: SideEffect.cpp
#include <iostream.h>

void Char_count ();   // counts characters read

int count;                // counts input lines
char ch;                  // input character




38
void main ()
{
  count = 0;
  ch = ' ';
  while ( !cin.eof() ) // a class function,
                       // checks for the end
                       // of file
  {
    count ++;
    Char_count ();
  }
  cout << count << " lines of input." << endl;
  return;
} // end of main ()



39
     void Char_count ()
     // counts the number of characters read
     {
       count = 0;              // side effect
       ch = ' ’;               // intialize ch
       while ((!cin.eof()) && (ch != '\n'))
       {
         cin >> ch;      // global variable access
         count ++;             // side effect
       } // end of while
       cout << count           // global access to count
            << " characters in this line." << endl;
       return;
     } // end of Char_count ()



40
     ESCAPE SEQUENCE
     \n   NEWLINE
     \t   HORIZONTAL TAB
     \r   CARRIAGE RETURN (CURRENT LINE)
     \a   ALERT (SYSTEM BELL)
     \\   BACKSLASH
     \”   DOUBLE QUOTE




41
      GLOBAL CONSTANTS
       AND SIDE EFFECTS
     IT IS ACCEPTABLE TO REFERENCE NAMED CONSTANTS

          GLOBALLY SINCE THE VALUES OF GLOBAL

         CONSTANTS CAN NOT BE CHANGED DURING

                  PROGRAM EXECUTION.

        THERE ARE TWO ADVANTAGES TO GLOBALLY

        REFERENCING CONSTANTS : EASE OF CHANGE

                   AND CONSISTENCY.
42
        LOCAL CONSTANTS

     IF A CONSTANT IS ONLY NEEDED IN ONE MODULE,

       THEN IT SHOULD BE DEFINED LOCALLY WITHIN

                    THAT MODULE.




43
           OBJECT LIFETIME
     AN EXECUTION-TIME CONCERN. REFERS TO LIFE
     SPAN OF OBJECTS DECLARED WITHIN FUNCTIONS.


     COVERS THE PERIOD OF TIME FROM THE
     CONSTRUCTION TO THE DESTRUCTION OF AN
     OBJECT.




44
     CONSTRUCTION OF DATA
           OBJECTS


     A MEMORY LOCATION IS ASSOCIATED WITH THE DATA
     OBJECT. THEN, THE DATA OBJECT IS INITIALIZED TO A
     SPECIFIC VALUE (EVENTUALLY).




45
EXAMINE THE DATA OBJECT counter IN THE
FOLLOWING CODE SEGMENT:

     {
         :
         int counter;
         :
         counter = 1;

         // the following is a loop
         while (counter <= 10)
         {
            :
         }
         :
     }

46
       THE CONSTRUCTION OF THE DATA OBJECT
       counter TOOK PLACE AS FOLLOWS :



     1. A MEMORY LOCATION WAS ASSOCIATED WITH counter.
     2. THAT MEMORY LOCATION WAS INITIALIZED TO 1




47
     DESTRUCTION OF DATA
          OBJECTS


     A MEMORY ALLOCATION IS DISASSOCIATED FROM THE
                     DATA OBJECT.




48
     WHAT INDICATES THE END OF counter LIFETIME?


     THE DESTRUCTION OF THE DATA OBJECT counter
      TAKES PLACE BY DISASSOCIATING IT FROM THE
                MEMORY ALLOCATION.




49
           STORAGE CLASSES
                   AUTOMATIC OBJECTS
       (DEFAULT STORAGE CLASS-- ALSO CALLED LOCAL)

     CONSTRUCTED WHEN EXECUTION ENTERS THE BLOCK IN
     WHICH THEY ARE DECLARED AND DESTROYED AT EXIT
     FROM SAME BLOCK.




50
                   STATIC OBJECTS

     CONSTRUCTED WHEN PROGRAM BEGINS EXECUTION
       AND DESTROYED WHEN PROGRAM TERMINATES.




51
     EXAMPLE: AUTOMATIC OBJECTS

       {
           int
                 i = 1;
                 :
       }




52
      while (logical_expression)
      {
         int
             i = 1;
             :
      }


     FOR EACH ITERATION, i IS CONSTRUCTED AT THE
     BEGINNING OF THE LOOP AND DESTROYED AT
     THE END !!!



53
         EXAMPLE: STATIC OBJECTS

        {
            static int
               i = 1;
               :
        }

     i IS CONSTRUCTED AT THE BEGINNING OF PROGRAM
     EXECUTION AND DESTROYED AT THE END.




54
                       Recursion
     A recursive function is a function that calls itself, either
         directly, or indirectly (through another function).

                 e.g. Factorial function (Fig 3.14)
                   Fibonacci function (Fig 3.15)




55
            Recursion VS Iteration
     Recursion is expensive in terms of processor time and
      memory usage than iteration.




56
     • Inline functions
     • Setting Default argument




57
             Function Overloading
     • You can use same function name as long as it has
       different signature than the other function that has same
       name.

     E.g. square function
     Or sqrt(int)
     Sqrt (long)
     Sqrt (double)




58

								
To top