Using conditional subtraction if a > b { b - a } else { 0 }
can lead to an unintended underflow, which can cause bugs or unexpected
behaviors. The saturating_sub
method ensures that the subtraction does not underflow by returning zero if the result would have been
negative.
Code examples
Noncompliant code example
let a = 12u32;
let b = 13u32;
let result = if a > b { b - a } else { 0 }; // Noncompliant: Potential underflow condition.
Compliant solution
let a = 12u32;
let b = 13u32;
let result = a.saturating_sub(b); // Compliant: Safe subtraction using saturating_sub.