2023-11-29 10:39:24 -05:00
|
|
|
---
|
2024-02-06 15:48:56 -05:00
|
|
|
minutes: 3
|
2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# Arithmetic
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn interproduct(a: i32, b: i32, c: i32) -> i32 {
|
|
|
|
return a * b + b * c + c * a;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
println!("result: {}", interproduct(120, 100, 248));
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
|
|
|
This is the first time we've seen a function other than `main`, but the meaning
|
|
|
|
should be clear: it takes three integers, and returns an integer. Functions will
|
|
|
|
be covered in more detail later.
|
|
|
|
|
|
|
|
Arithmetic is very similar to other languages, with similar precedence.
|
|
|
|
|
|
|
|
What about integer overflow? In C and C++ overflow of _signed_ integers is
|
2024-06-10 16:18:25 +02:00
|
|
|
actually undefined, and might do unknown things at runtime. In Rust, it's
|
|
|
|
defined.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
Change the `i32`'s to `i16` to see an integer overflow, which panics (checked)
|
2023-12-31 00:15:07 +01:00
|
|
|
in a debug build and wraps in a release build. There are other options, such as
|
|
|
|
overflowing, saturating, and carrying. These are accessed with method syntax,
|
|
|
|
e.g., `(a * b).saturating_add(b * c).saturating_add(c * a)`.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
In fact, the compiler will detect overflow of constant expressions, which is why
|
|
|
|
the example requires a separate function.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
</details>
|