Skip to the task
Layout
Back to classic view

You are looking at lesson 3. Your place is still Practice test 1, task 1: About.

READTask 12 of 22 · step 6: Common mistakes

Common mistakes

Eight mistakes with conditions and loops, and how to spot them from the compiler's messages.

Mistakes with conditions and loops would often compile without any warning. The course flags catch most of them, so learn to recognise the messages.

Common mistakes
  • = instead of ==. suggest parentheses around assignment used as truth value: there is an assignment in the condition.
  • ; after if. if (x >= 5);: the condition ends at the ;, and the { } always runs. GCC: suggest braces around empty body in an 'if' statement.
  • ; after for or while. for (...); spins an empty loop, and the body runs once after it. GCC: this 'for' clause does not guard....
  • A forgotten break. this statement may fall through: without break, the next case's code runs too.
  • 5 <= x <= 10. comparisons like 'X<=Y<=Z' do not have their mathematical meaning. Write 5 <= x && x <= 10.
  • A loop without an end. The program "hangs": nothing inside the loop changes the condition (a forgotten i++ or a new read_int). Stop it with ■ (Ctrl+F2).
  • One time too many or too few. for (int i = 0; i <= n; i++) repeats n + 1 times. From 0 use i < n, from 1 use i <= n.
  • Division by 0. When the loop didn't run even once, sum / count divides by 0. Check count before the loop.