2

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
mcarton
  • 27,633
  • 5
  • 85
  • 95
Muhammad Naufil
  • 2,420
  • 2
  • 17
  • 48
  • 3
    Careful with your notations: `2e31` is 2 × 10^31 = , not 2^31. `2e31 - 1` is 19999999999999999999999999999999 (modulo rounding error). – trent Apr 20 '19 at 12:58

1 Answers1

8

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mcarton
  • 27,633
  • 5
  • 85
  • 95