Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to the use of casting:

Rule 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);   // 32-bit int assumed.

Reasoning

Casting is dangerous. In the example above, unsigned 16-bit sample can take a larger range of positive values than a signed 16-bit integer. In that case, the absolute value will be incorrect as well. Thus there is a possible loss of precision (i.e., overflow) if int is only 16 bit, as the C standard permits.

Exceptions

None.

Enforcement

These rules shall be enforced during code reviews.

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

Sign up for our newsletter today!

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.