EXERCISES ON C FUNCTIONS READING ------- Notes for lecture 2. Kernighan and Ritchie, 1.7, 1.8 Sedgewick, p. 73 SUPPLEMENTAL READING -------------------- Deitel and Deitel, 5.1-5.5 EXERCISES --------- 1. What is wrong with the following C function? int square (int x); { return x*x; } 2. Write a C function that takes a positive integer N as argument and returns the largest power of two less than or equal to N. 3. What value is printed out by the following program? #include int f(int x) { return x+2; } main() { int x = 5; printf("%d \n", f(x+2)); } 4. Run the following program through the compiler to see the error messages that lcc (or cc) produces for semicolon errors. int square (int x); { return x*x; } main() { int a, b, c; c = 0 b = 0; if (a > b) c = 0 else b = 0; } . . . . ANSWERS TO EXERCISES ON C FUNCTIONS 1. Extra semicolon on the first line. Only function prototypes have semicolons after the parenthesis, not function definitions. 2. int f(int N) { int j; for (j = 1; j <= N; j += j) ; return j/2; } 3. Prints out "9". 4. Different compilers have different ways of trying to tell you about the problems. % cc bad.c "bad.c", line 2: syntax error before or at: { "bad.c", line 2: undefined or not a type: x "bad.c", line 2: warning: old-style declaration or incorrect type for: x "bad.c", line 2: identifier redeclared: x current : pointer to int previous: function(void) returning int : "bad.c", line 2 "bad.c", line 2: syntax error before or at: } "bad.c", line 7: syntax error before or at: b "bad.c", line 8: syntax error before or at: else cc: acomp failed for bad.c % lcc bad.c bad.c:2: unrecognized declaration bad.c:2: unrecognized declaration bad.c:2: syntax error; found `*' expecting `;' bad.c:2: redeclaration of `x' previously declared at bad.c:2 bad.c:2: unrecognized declaration bad.c:7: syntax error; found `b' expecting `;' bad.c:8: syntax error; found `else' expecting `;' bad.c:9: warning: missing return value % gcc bad.c bad.c:2: parse error before `{' bad.c: In function `main': bad.c:7: parse error before `b' bad.c:8: parse error before `else' % Compilers do the best they can to try to understand what we give them to be legal C programs. When we make errors, their interpretation may diverge from our intention, to the point that the error messages may not make sense to us. Lesson: fix the *first* error, then try again.