Muhammad Naufil
Muhammad Naufil

Reputation: 2637

Why do I not get a literal out of range error when storing a number larger than an i32 into a variable?

The Rust documentation says the default integer type is i32, which means the biggest number a variable can save by default is 2147483647 i.e 2e31 - 1 . This turned out to be true too: if I try to save greater number than 2e31 - 1 in the x variable, I get the error literal out of range.

Code

fn main() {
    let x = 2147483647;
    println!("Maximum signed integer: {}", x);
    let x = 2e100;
    println!("x evalues to: {}", x);
}

but why do I not get error if I save value 2e100 in the x variable? It surely evaluates to greater than 2e31 - 1.

Output

Maximum signed integer: 2147483647
x evalues to: 20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Code

fn main() {
    let x = 2147483648;
    println!("Maximum signed integer: {}", x);
}

Output

error: literal out of range for i32
 --> src/main.rs:2:11
  |
2 |     let x=2147483648;
  |           ^^^^^^^^^^
  |
  = note: #[deny(overflowing_literals)] on by default

Upvotes: 2

Views: 950

Answers (1)

mcarton
mcarton

Reputation: 29991

Constant literals such as 2e100 are not integer literals but floating point literals. This can be shown with

fn main() {
    let () = 2e100;
}

which produces

error[E0308]: mismatched types
 --> src/main.rs:2:9
  |
2 |     let () = 2e100;
  |         ^^ expected floating-point number, found ()
  |
  = note: expected type `{float}`
             found type `()`

See also:

Upvotes: 8

Related Questions