← All lints

neg_mod_fixup

L0527Idiomswarn

C++ negative-remainder fixup

(a - b + m) % m: % never returns a negative, so (a - b) % m is enough

Flagged
let n: 1..=100 = read()
let a: Int = read()
let b: Int = read()
print((a - b + n) % n, (a % n + n) % n, ((a % 7) + 7) % 7)
Write instead
let n: 1..=100 = read()
let a: Int = read()
let b: Int = read()
print((a - b) % n, a % n, a % 7)

Why

C++ % takes the sign of the dividend, so C++ code writes (a - b + m) % m or (a % m + m) % m to get a value in 0..m. CP Lang's integer % is Euclidean: a % m is already in 0..abs(m) for every sign of a and m, so the + m only adds a term that can overflow and makes the reader wonder what it guards. The fix drops it (and the outer % m when the inside is already x % m); it applies when the divisor is a literal or a name or field of a signed integer type, where the two forms agree for every input. When the whole computation is modular arithmetic, Mod<P> removes the remainders altogether.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.mod: modular arithmetic and combinatorics.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=100 = read()
let a: Int = read()
let b: Int = read()
print((a - b + n) % 7, (a + 1) % n, (a - b + 2 * n) % n)

Turn it off

For one block, wrap it in with lint(neg_mod_fixup: allow):. For a project, add neg_mod_fixup = "allow" under [lints] in cp.toml.

Generated from spec/lints/neg_mod_fixup, the same record the linter is built from.