Simple questions on integers

While reading a few chapters of the book and doing simple programs, I noticed some things that I'm not sure of.

  1. Integer literals like 0 are by default i32 but they get coerced when they are compared with other types (e.g. i64var > 0).
  2. When the values are non negative, it is recommended to use unsigned integers. I remember watching a video in which Stroustrup recommended using signed integers in c++ unless you really have to use unsigned. A shed of light on this please. I'm not an experienced programmer and have a shallow knowledge of programming as a whole.

Integer literals are not i32 by default, and i32 does not coerce into other integer types. The compiler will try to infer which integer type you want, which is why compiler errors talk about {integer} in error messages:

error[E0599]: no method named `foo_bar` found for type `{integer}` in the current scope
 --> src/
4 |     a.foo_bar();
  |       ^^^^^^^ method not found in `{integer}`

That said, if it is in a situation where every integer type could work, it will just pick i32 by default.

As for the signed-unsigned thing, well Rust disagrees with Stroustrup on that point :woman_shrugging:.

Thanks for the clarification! Now I'll feel more comfortable using unsigned.

On the signed-unsigned thing, Stroustrup reccomends that for C++ as a way to avoid undefined behaviour (signed integer overflow is UB). Since Rust doesn't have this form of UB (overflow panics on debug, and wraps on release), we don't have to care too much if the integer is signed or unsigned.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.