home *** CD-ROM | disk | FTP | other *** search
/ Jason Aller Floppy Collection / 98.img / LCNOW2.ZIP / EXAMPLES / SWAP.C < prev    next >
C/C++ Source or Header  |  1988-08-02  |  2KB  |  94 lines

  1. /*
  2.  * S W A P
  3.  *
  4.  * Exchange values in storage by using "call-by-value" and
  5.  * "call-by-reference" parameter-passing methods to show
  6.  * the fundamental difference between the methods.
  7.  */
  8.  
  9. #include <stdio.h>
  10.  
  11. int
  12. main(void)
  13. {
  14.     int val1, val2;         /* integer values */
  15.  
  16.     /*
  17.      * Function prototypes.
  18.      */
  19.     void SwapByValue(int, int);
  20.     void SwapByReference(int *, int *);
  21.  
  22.     /*
  23.      * Initialize variables.
  24.      */
  25.     val1 = 10;
  26.     val2 = 20;
  27.     puts("Parameter-passing test\n");
  28.     printf("Starting values:\n\tval1 = %d;  val2 = %d\n",
  29.         val1, val2);
  30.  
  31.     /*
  32.      * Pass parameters by value.
  33.      */
  34.     puts("After call-by-value attempt:");
  35.     SwapByValue(val1, val2);
  36.     printf("\tval1 = %d;  val2 = %d\n", val1, val2);
  37.  
  38.     /*
  39.      * Pass parameters by reference.
  40.      */
  41.     puts("After call-by-reference attempt:");
  42.     SwapByReference(&val1, &val2);
  43.     printf("\tval1 = %d;  val2 = %d\n", val1, val2);
  44.  
  45.     return (0);
  46. }
  47.  
  48.  
  49. /*
  50.  * SwapByValue()
  51.  *
  52.  * Attempt to swap two variables in memory by using
  53.  * call-by-value parameter passing.
  54.  */
  55.  
  56. void
  57. SwapByValue(int v1, int v2)
  58. {
  59.     int tmp;        /* swap buffer */
  60.  
  61.     /*
  62.      * Swap the values of v1 and v2.  Because v1 and v2
  63.      * are copies of the actual arguments, the variables
  64.      * in main() are unaffected by this action.
  65.      */
  66.     tmp = v1;
  67.     v1 = v2;
  68.     v2 = tmp;
  69. }
  70.  
  71.  
  72. /*
  73.  * SwapByReference()
  74.  *
  75.  * Attempt to swap two variables in memory by using
  76.  * call-by-reference parameter passing.
  77.  */
  78.  
  79. void
  80. SwapByReference(int *vp1, int *vp2)
  81. {
  82.     int tmp;        /* temporary variable for use in swap */
  83.  
  84.     /*
  85.      * Swap the values in the variables pointed to by
  86.      * vp1 and vp2.  Because vp1 and vp2 are addresses of
  87.      * the actual arguments, the values in main() are
  88.      * changed by this action.
  89.      */
  90.     tmp = *vp1;
  91.     *vp1 = *vp2;
  92.     *vp2 = tmp;
  93. }
  94.