I am in a position where I must strictly adhere to AUTOSAR’s C++ coding rules, and I am troubled by them every day. One day, while checking the rules, I noticed something strange about the sample for A4-7-1.
The purpose of Autosar’s A4-7-1 is as follows:
Rule A4-7-1 (required, implementation, automated)
An integer expression shall not lead to data loss.
The following sample is provided:
std::int8_t Fn1(std::int8_t x, std::int8_t y) noexcept { return (x + y); // Non-compliant - may lead to overflow}std::int8_t Fn2(std::int8_t x, std::int8_t y) { if (x > 100 || y > 100) // Range check { throw std::logic_error("Preconditions check error"); } return (x + y); // Compliant - ranges of x and y checked before the arithmetic operation}
Why is Fn2 considered compliant? For example, if x=80 and y=60, wouldn’t it still overflow?
When I tried Fn2(60,80) in my x86-64 PC, it returns negative value.