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/04/

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 04 main.c Code Diff
UNCHANGED This step does not change this file.
#include <stdio.h>
#include "input.h"
int main(void) {
int grade = read_int("Grade (0 - stop): ");
int sum = 0;
int count = 0;
while (grade != 0) {
sum += grade;
count++;
grade = read_int("Grade (0 - stop): ");
}
if (count > 0) {
printf("Average: %.2f\n", (double)sum / count);
} else {
printf("No grades.\n");
}
return 0;
}