Lab overview
Lab 01
Lab 02
Lab 03
Lab 04
Lab 05
Lab 06
Lab 07
Lab 08
Lab 09
Lab 10
Lab 11
Lab 12
Lab 13
Review

[Course home page]

CSC 209 lab 10 solutions, week of 19 July 2022

Question 6:

Comment on the use of the cast in the following code. The "..." represents some number of lines of code.
statbuf.st_mtime might not be a long — it could be int, or even a non-standard type used by this particular compiler; but we want to store it in a variable and we have reason to believe that a variable of type "long" will be appropriate.

    long t;
    ...
    if (stat(filename, &statbuf)) {
        perror(filename);
        exit(1);
    }
    t = (long)statbuf.st_mtime;
    ...

Solution:

That cast is bad and should be omitted. The code functions fine without it — an assignment is a conversion to the type of the variable. (So is a return from a function a conversion to the declared return type of the function.)

Why it's bad is illustrated by mistakes with, for example, levels of indirection:

    t = (long)&statbuf.st_mtime;

This assigns t to be an integer representation of the address of the st_mtime member of statbuf, which is surely not what's intended. With the cast, though, it will execute and perform this incorrect task. Without the cast, it will give a fatal error message.

Errors are bad, but error messages are good (because they allow you to fix the errors, and errors are bad). Casts suppress error messages, so that is bad. Casts are only needed very very occasionally in C. Only use a cast if necessary. If you're not sure, leave it out (and you will almost certainly find that it's not necessary).


[press 'back' in your web browser to return to the problems]