Noteworthy examples of code

Collection of some pearls of code collected while checking the exams of the C programming courses at the University of Pavia.

The course is attended by first-year undergraduated students. They are listed in no particular order. The code is internationalized using English terms but preserves the original ideas behind it.

NOTE: the title and the content of this page is quite ironic, so do not expect to find any holy light to your programming skills. But maybe some how-do-not-to and some smile.

Overkill use of loops

The following one-iteration loop has been used to read the first line of a text file:

for (i = 0; i < 1; i++) {
    fgets(buf, sizeof(buf), f);
    sscanf(buf, "%d %d", &var1, &var2); 

Do you see the need of the loop?

Counting the numbers within intervals: the hard way

Here it was asked to count the number of times a number, whose value is between 1 and 100, is included in the intervals [1..10], [11..20], …, [91..100].

The idea to use an array called count and to increment the corresponding element when number is within a given range is fine. However, the following implementation goes along the hard way:

if (1 <= number && number <= 10)
else if (11 <= number && number <= 20)
else if (21 <= number && number <= 30)
else if (31 <= number && number <= 40)
else if (41 <= number && number <= 50)
else if (51 <= number && number <= 60)
else if (61 <= number && number <= 70)
else if (71 <= number && number <= 80)
else if (81 <= number && number <= 90)
else if (91 <= number && number <= 100)

Can you imagine what could happen if number would have been in the range [1..1000000]?

Counting the numbers within intervals - part 2: a little bit softer way (with solution)

Same problem as above. Solved with a dedicated data structure and a loop.

/* data structures */

struct limits
    int min;
    int max;

struct limits intervals[10] = {{1,10},{11,20},{21,30},{31,40},{41,50},{51,60},{61,70},{71,80},{81,90},{91,100}};

/* ..... */

    /* the logic */

    for (k = 0; k < 10; k++)
        if ((number <= intervals[k].max) && (number >= intervals[k].min))

This method would be perfect if the intervals would not be so regular.

However, in the considered case, a more concise solution is possible:

count[(number - 1) / 10]++;

Weak error checking

After trying to open a file, error checking is done as follows:

FILE *f = fopen(myfile, "r");

if (f == NULL) {
    printf("File can not be opened for reading\n");
/* ... code goes on with regular file reading ... */

Forgot a return -1 or retunr NULL, or some similar error signaling statement, within the if block…

This program is going to fail in case of missing file.