/* * SWAP -- demonstrate how pointers work as parameters to functions * * Usage: swap * * Inputs: none * * Outputs: lines showing 2 values before and after swapping with and * without pointers * * Exit Code: 0 (always succeeds) * * written for ECS 030, Fall 2015 * * Matt Bishop, Oct. 14, 2015 * revision from an earlier program * */ #include /* * swap two elements (no pointers) */ void npswap(int x, int y) { int temp; /* temporary */ /* * show what they are on entry */ printf("begin npswap: elem1 is %d, elem2 is %d\n", x, y); /* * do the swap */ temp = x; x = y; y = temp; /* * show they were exchanged */ printf(" end npswap: elem1 is %d, elem2 is %d\n", x, y); } /* * swap two elements (pointers) */ void pswap(int *x, int *y) { int temp; /* temporary */ /* * show what they are on entry */ printf("begin pswap: elem1 is %d, elem2 is %d\n", *x, *y); /* * do the swap */ temp = *x; *x = *y; *y = temp; /* * show they were exchanged */ printf(" end pswap: elem1 is %d, elem2 is %d\n", *x, *y); } /* * this is to show that everything is call by value * so you need to simulate call by reference * it uses swapping */ int main(void) { int elem1 = 4; /* first element */ int elem2 = 5; /* second element */ /* * say what you're starting with */ printf(" initial: elem1 is %d, elem2 is %d\n", elem1, elem2); /* * use the non-pointer swap and print the results */ npswap(elem1, elem2); printf("after npswap: elem1 is %d, elem2 is %d\n", elem1, elem2); /* * use the pointer swap and print the results */ pswap(&elem1, &elem2); printf("after pswap: elem1 is %d, elem2 is %d\n", elem1, elem2); /* * say goodbye */ return(0); }