-1

How can I do overflow check in all steps of a

fn somemath() -> u32 {
   let x: u32 = y * 3 + 2;
   return x
}

something similar to

fn somemath() -> u32 {
    let x: u32 = y.checked_mul(3).checked_add(2)
    return x
}

Or what is the best practice, to avoid overflow in such cases? In the end I need x to be not producing overflow and be a valid result or produce error and can the function return u32 if successfull?

user3338991
  • 431
  • 2
  • 5
  • 9
  • You'll probably have to break it down into steps, because you need to check the `Option` returned from the `checked_*` functions. – Herohtar Mar 15 '20 at 22:36
  • Do you want to return a `u32`? Or an `Option`? If later, you can use the [`?` operator](https://stackoverflow.com/questions/42917566/what-is-this-question-mark-operator-about), if former, you can chain the function calls with [`and_then`](https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then). – hellow Mar 16 '20 at 06:50

1 Answers1

0

It's up to you to decide whether the check is necessary, and what do do when it overflows.

If there's no meaningful result if the overflow happens, you can return Option::None for example:

fn somemath(y: u32) -> Option<u32> {
    let x: u32 = y.checked_mul(3)?.checked_add(2)?;
    return Some(x);
}

fn somemath(y: u32) -> Option<u32> {
    y.checked_mul(3)?.checked_add(2) // same, but shorter
}

You could also check whether inputs are small enough that overflow will never happen. Or you could use a larger type for intermediate values (e.g. u64 here) to get a valid result for any u32 input.

Kornel
  • 97,764
  • 37
  • 219
  • 309