/* goodSwap.c - in class exercise solution - int swap via pointer args and passing addresses of actual parameters */ #include #include /* functions must either be declared (via prototype) or defined before use here we just define it first */ /* GETINTS: prompts for and returns 2 ints return value of 0 means both ints successfully gotten from kbd any other value indicates an error. return vals not to be used */ int getInts(int *a, int *b) { #define EXPECTED_CONVERSIONS 2 printf("Enter %d ints separated by whitespace: ", EXPECTED_CONVERSIONS); /* Note below we don't put '&' before a and b as they are addresses */ return scanf("%d %d", a, b) - EXPECTED_CONVERSIONS; } /* SWAPINTS: uses addresses/pointers to exchange values of incoming arguments */ void swapInts(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* PRINT: argument values are copied in, no modification, no need to pass addresses */ void printInts(int a, int b) { printf("1st arg= %d 2nd arg= %d\n", a, b); } /*........................M A I N F U N C T I O N........................*/ int main(int argc, char *argv[]) { int x, y; /* compiler does not guarantee initialized to zero or anything else */ if (getInts(&x, &y)) /* in C, any non-zero value is TRUE, only zero is FALSE */ { fprintf(stderr,"Conversions failed. Program exiting.\n\n"); exit(EXIT_FAILURE); } printf("\nBefore swap: "); printInts(x, y); swapInts(&x, &y); printf("\nAfter swap: "); printInts(x, y); return EXIT_SUCCESS; }