Barr Group TwitterBarr Group Vimeo

Rules:

1.6.a. Each cast shall feature an associated comment describing how the code ensures proper behavior across the range of possible values on the right side.

Example:

int
abs (int arg)
{
    return ((arg < 0) ? -arg : arg);
}

...
    uint16_t sample = adc_read(ADC_CHANNEL_1);
    result = abs((int) sample);             // WARNING: 32-bit int assumed.

Reasoning: Casting is dangerous. In the example above, unsigned 16-bit “sample” can hold larger positive values than a signed 16-bit integer. In that case, the absolute value will be incorrect as well. Thus there is a possible overflow if int is only 16-bits, which the ISO C standard permits.

Enforcement: This rule shall be enforced during code reviews.