CSC 101 Lecture Notes Week 8
Review of Program 4 Testing
More on Function Parameters,
including parameters to main
Relevant Reading: Chapters 6 (again) and 13
#include <string.h> #include <stdio.h> /**** * * Implementation and testing a C function that wants to exchange the value of * two integer variables. Unfortunately, this function does not work as * intended. See the file exchange.c for a version that does work. * */ void exchange(int x, int y) { int tmp; /* Hold the value of x temporarily */ tmp = x; x = y; y = tmp; } int main() { int i = 10; int j = 20; printf("i,j before exchange = %d,%d\n", i, j); exchange(i, j); printf("i,j after exchange = %d,%d\n", i, j); return 0; }
Figure 1: Main and exchange memory just before exchange returns; changing x and y had no effect on i and j.
#include <string.h> #include <stdio.h> /**** * * Implementation and testing a C function that exchanges the value of two * integer variables. It illustrates the concept of formal output parameters, * covered in Section 6.4 of the book. * */ void exchange(int *x, int *y) { int tmp; /* Hold the value of x temporarily */ tmp = *x; *x = *y; *y = tmp; } int main() { int i = 10; int j = 20; printf("i,j before exchange = %d,%d\n", i, j); exchange(&i, &j); printf("i,j after exchange = %d,%d\n", i, j); return 0; }
Figure 2: Main and exchange memory just before exchange returns.
#include <stdio.h> #include <stdlib.h> /**** * * Read command-line arguments and convert them to ints. Invoke this program * from the terminal like this, for example: * * cmd-line 10 20 30 * * assuming that the program has been compiled with "gcc ... -o cmd-line". The * output with this invocation is this: * * arg[1] = 10 * arg[2] = 20 * arg[3] = 30 * */ int main(int argc, char** argv) { int i; int val; char* arg; for (i = 1; i < argc; i++) { arg = argv[i]; val = atoi(arg); printf("arg[%d] = %d\n", i, val); } return 0; }