/*
 * exchange.c
 * Author: Chris Beck
 *
 * Demonstrates variations on parameter passing.
 */

#include <stdio.h>

/* function prototypes */

void exchange1(int, int);
void exchange2(int *, int *);
void exchange3(int *, int *);

int main()
{
  int i = 1, j = 2;
  
  printf("Before exchange1:\ti == %d\tj == %d\n",i,j);
  exchange1(i,j);
  printf("After exchange1:\ti == %d\tj == %d\n\n",i,j);

  i = 1;
  j = 2;
  printf("Before exchange2:\ti == %d\tj == %d\n",i,j);
  exchange2(&i,&j);
  printf("After exchange2:\ti == %d\tj == %d\n\n",i,j);
  
  i = 1;
  j = 2;
  printf("Before exchange3:\ti == %d\tj == %d\n",i,j);
  exchange3(&i,&j);
  printf("After exchange3:\ti == %d\tj == %d\n\n",i,j);
}

void exchange1(int i, int j)
{
  /* Pass by value means that the value of i and j in main will be passed to
   * exchange1.  Inside exchange1 the values will be exchanged but this will
   * not effect i and j in the main program.
   */

  int tmp;
  tmp = i;
  i = j;
  j = tmp;
  
  printf("Inside exchange1:\ti == %d\tj == %d\n",i,j);
}

void exchange2(int *i, int *j)
{
  /* exchange2 takes, as parameters, pointers to integers. i in exchange2
   * points to i in the main program while j in exchange2 points to j in the
   * main program.  Here we exchange the value of what i is pointing at with
   * the value of what j is pointing at and so the exchange is reflected in
   * the main program
   */

  int tmp;
  tmp = *i;
  *i = *j;
  *j = tmp;
  
  printf("Inside exchange2:\ti == %d\tj == %d\n",*i,*j);
}


void exchange3(int *i, int *j)
{
  /* exchange3 takes pointer like exchange2 however it does not exchange what
   * is pointed to by i and j rather it exchanges the pointers themselves.
   * What i was pointing at as the function begins in pointed to be j after
   * the exchange (and vice versa).  However since we are just exchanging
   * pointers nothing changes with i and j in main
   */

  int *tmp;
  tmp = i;
  i = j;
  j = tmp;

  /* Question:  What happens if the line I stick the following line here:
                 *j = 3;
   * (uncommented of course).  Why does this happen?
   */

  printf("Inside exchange3:\ti == %d\tj == %d\n",*i,*j);

}
