← All lints

manual_digit_loop

L0544Idiomswarn

C++ digit loop

while y > 0: .. y % 10 .. y /= 10: y.digits() lists the digits

Flagged
let x: 1..=1000000000000000000 = read()
var s = 0
var y = x
while y > 0:
    s += y % 10
    y /= 10
print(s)
Write instead
let x: 1..=1000000000000000000 = read()
print(x.digits().sum())

Why

C++ takes a number apart with while (y > 0) { d = y % 10; y /= 10; }. x.digits() from std.math is the list of digits, lowest first (x.digits(base: b) in another base), so a digit sum is x.digits().sum() and any other per-digit work is a for d in x.digits() loop over a value that is never mutated. There is no automatic fix; base 2 is left alone, where bit and std.bits are the better spelling.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

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

Near miss
let x: 1..=1000000000000000000 = read()
var s = 0
var y = x
while y > 0:
    s += y % 2
    y /= 2
print(s)

Turn it off

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

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