Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid range causes loop to be skipped. #51692

Closed
arp2600 opened this issue Jun 21, 2018 · 1 comment
Closed

Invalid range causes loop to be skipped. #51692

arp2600 opened this issue Jun 21, 2018 · 1 comment

Comments

@arp2600
Copy link

arp2600 commented Jun 21, 2018

In a for loop with a range, if the range value is assigned to a type to small for the range, the loop will be skipped.

I tried this code:

fn main() {
    let mut counter: u64 = 0;
    for i in 0..256 {
        println!("i = {}", i);
        let x: u8 = i;
        counter += 1;
    }
    
    println!("looped {} times", counter);
}

Expected output:

i = 0
i = 1
...
i = 255
looped 256 times

Actual output:

looped 0 times

A warning is given that the literal is out of range, but I would have expected this to be a compilation error.

warning: literal out of range for u8
 --> src/main.rs:4:17
  |
4 |     for i in 0..256 {
  |                 ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

Commenting out the line let x: u8 = i; causes the code to run correctly.

I tried this on stable and nightly with debug and release.
Below I've included a link to the rust playground demonstrating the issue.
https://play.rust-lang.org/?gist=36c8b0e6a621a419311cbfec1ce9cdcb&version=undefined&mode=undefined

@oli-obk
Copy link
Contributor

oli-obk commented Jun 21, 2018

Duplicate of #47213

@oli-obk oli-obk marked this as a duplicate of #47213 Jun 21, 2018
@oli-obk oli-obk closed this as completed Jun 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants