-
-
Save rust-play/6be3d72bea6aa79bad8e9ff51c3dacb0 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let max_usize = std::usize::MAX; | |
println!("std::usize::MAX/2: {}", std::usize::MAX / 2); | |
if !is_debug() { | |
let overflow_release = max_usize.wrapping_add(1); | |
println!("Overflow: {}", overflow_release); // Output in release: 0 | |
} else { | |
#[warn(arithmetic_overflow)] | |
#[cfg(debug_assertions)] | |
let overflow_debug = max_usize + 1; | |
#[cfg(debug_assertions)] | |
println!("Overflow (debug): {}", overflow_debug); | |
} | |
// Explicit wrapping operations | |
let wrapped_add = max_usize.wrapping_add(std::usize::MAX / 2 + 1); | |
println!("Wrapped add: {}", wrapped_add); | |
let wrapped_mul = 1_usize.wrapping_mul(std::usize::MAX / 2 + 0); | |
println!("Wrapped mul: {}", wrapped_mul); | |
} | |
fn is_debug() -> bool { | |
if cfg!(debug_assertions) { | |
println!("Debug build."); | |
true | |
} else { | |
println!("Release build."); | |
false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment