This article continues the one published two weeks ago: Top 101 mistakes done by novice programmers C and Top 101 mistakes done by novice programmers C – part 2 


8. Forgetting to put a break in a switch statement

Remember that C does not break out of a switch statement if a case is encountered. For example:

int x = 1;
switch(x) {
case 1:
case 2:
case 3:
prints out:


9. Size of arrays

Arrays in C always start at index 0. This means that an array of 10 integers defined as:

int a[10];

has valid indices from 0 to 9 not 10! It is very common for students go one too far in an array. This can lead to unpredictable behavior of the program.

10. Integer division

The C language uses the / operator for both real and integer division. If both operands are of an inte type, integer division is used, else real division is used. For example:

double aHalf = 1/2;

This code sets half to 0 not 0.5! Why? Because 1 and 2 are integer constants. To have a float or double division you have to do the following:

float  aHalf = 1.0/2;
double aHalf = 1.0/2;


11. Loop errors

In C, a loop repeats the very next statement after the loop statement. The code:

int n = 10;
is an infinite loop.
The semicolon after the while defines the statement to repeat as the null statement (which does nothing). Remove the semicolon and the loop works as expected.

Another common loop error is to iterate one too many times or one too few. Check loop conditions carefully!

12. Null terminated strings


12.a Not null terminating strings

C assumes that a string is a character array with a terminating null character. This null character has ASCII value 0 and can be represented as just 0 or '\0'. This value is used to mark the end of meaningful data in the string. If this value is missing, many C string functions will keep processing data past the end of the meaningful data and often past the end of the character array itself until it happens to find a zero byte in memory!

12.b Not leaving room for the null terminator

A C string must have a null terminator at the end of the meaningful data in the string. A common mistake is to not allocate room for this extra character. For example, the string defined below

char str[30];

only has room for only 29 (not 30) actually data characters, since a null must appear after the last data character.




Part four in the next fifteen days.