Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Functions.

READTask 13 of 23 · step 6: Common mistakesCommon mistakes
Common mistakes in practice/05/

Eight mistakes with functions, assert and recursion.

Details & hint

With functions the compiler checks more: whether the function is declared, whether there are as many arguments as needed, whether every path returns a value. A few mistakes are left to you.

Common mistakes
  • A function used before it is declared. implicit declaration of function 'round_to_int': the function is written below main. Move it above, or write a prototype above main.
  • Not every path returns a value. control reaches end of non-void function: e.g. an if with a return, but no return after it. A function that isn't void must return a value in every case.
  • The wrong number of arguments. too few arguments to function 'round_to_int' (or too many). Below it, note: declared here shows how many parameters the function has.
  • Expecting the function to change a variable. double_it(a) doesn't change a: the parameter is a copy. Return the result: a = double_it(a);.
  • The result thrown away. round_to_int(average); with no assignment or printf: the result is computed and lost. The compiler doesn't warn about it.
  • () instead of (void). int read_grade() compiles, but then read_grade(5) would compile too. Write (void).
  • Recursion without a base case. exit code -1073741571 (0xC00000FD): the call stack overflowed. Check that every call gets closer to the base case.
  • An action inside assert. assert(read_int("How many? ") > 0) disappears in Release mode, together with the question. Only checks go inside assert.
practice 05 recursion.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
/* The digit sum; depth is how many calls deep the function already is.
Before: n >= 0, depth >= 0.
After: the sum of the digits of n. */
int digit_sum(int n, int depth) {
assert(n >= 0 && depth >= 0);
printf("%*sdigit_sum(%d)\n", depth * 2, "", n);
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10, depth + 1);
}
/* n! = 1 * 2 * ... * n.
Before: n is from 0 to 20 (21! doesn't fit in a long long).
After: the factorial of n; 0! = 1. */
long long factorial(int n) {
assert(n >= 0 && n <= 20);
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
int sum = digit_sum(472, 0);
printf("Digit sum: %d\n", sum);
printf("5! = %lld\n", factorial(5));
printf("20! = %lld\n", factorial(20));
return 0;
}