Warn about C-style octal literals by GrigorenkoPV · Pull Request #131309 · rust-lang/rust (original) (raw)
Uplifts clippy::zero_prefixed_literal
as leading_zeros_in_decimal_literals
, warn-by-default.
The leading_zeros_in_decimal_literals
lint detects decimal integral literals with leading zeros.
Example
fn is_executable(unix_mode: u32) -> bool { unix_mode & 0111 != 0
Explanation
In some languages (including the infamous C language and most of its family), a leading zero marks an octal constant. In Rust however, a 0o
prefix is used instead.
Thus, a leading zero can be confusing for both the writer and a reader.
In Rust:
fn main() { let a = 0123; println!("{}", a); }
prints 123
, while in C:
#include <stdio.h>
int main() { int a = 0123; printf("%d\n", a); }
prints 83
(as 83 == 0o123
while 123 == 0o173
).
Notes
Compared to the Clippy lint, this will not warn if the literal is unambiguous, i.e. it has 8's or 9's in it (clearly not octal) or it is <10 (in this case the value does not depend on the base).