← All lints

sentinel_scalar

L0536Idiomswarn

Scalar started at a sentinel

var found = -1 / var best = -10**18: var found: ?Int = None

Flagged
let n: 1..=100 = read()
let a: [0..n]Int = read()
var last = -1
for i in 0..n:
    if a[i] == 0:
        last = i
print(last)
Write instead
let n: 1..=100 = read()
let a: [0..n]Int = read()
var last: ?Int = None
for i in 0..n:
    if a[i] == 0:
        last = i
print(last ?? -1)

Why

C++ starts "the index found so far" at -1 and "the best so far" at -1e18, because an int has no value for "nothing yet". Both are real numbers: -1 indexes from the end in Python habits and passes any >= -1 test, and -10**18 is only a guess at a bound the data may pass. CP Lang has the value C++ lacks: var found: ?Int = None starts with nothing, found = i sets it, and the reader must say what nothing means (found ?? -1, if let, !). For a running best, a.max() or .min() from std.seq returns ?T and needs no start at all. The lint fires on a scalar var started at -1 and later set to a name inside a for loop, or started at a value of size at least 10**9 and set inside a for loop. A while loop's bound (var hi = 10**18 in a binary search) is not a sentinel and is left alone. It has no fix, since each read of the variable changes.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: O. Optionals and sentinels.

Not flagged

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

Near miss
let n: 1..=100 = read()
var sign = -1
for i in 0..n:
    sign = -sign
var (lo, hi) = (0, 10**18)
while hi - lo > 1:
    let mid = (lo + hi) / 2
    if mid * mid <= n: lo = mid else: hi = mid
print(sign, lo)

Turn it off

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

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