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.

What’s happening and how it’s done. Get in the know.

Sign Up for Our Newsletter

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.