1. 24

  2. 4

    sqr is a place where one might be tempted to use a macro in C, but writing such a macro in a way that x doesn’t get evaluated twice is tricky.

    No, you really wouldn’t, unless you’re dealing with C code from the 80s when compilers weren’t so good or that’s supposed to run on some tiny embedded system or some other unusual edge case. Any compiler from the last 30 years will inline a tiny function like that almost without thinking about it and most C programmers know that.

    1. 2

      Yeah this part is weird. Rust works the same as C in this regard, because to my knowledge it’s LLVM doing the work here.

      1. 2

        Even powf(x, 2.0f) seems to compile down to x*x on GCC even though it’s not so tiny. So yeah, no macros needed.

        1. 1

          No, you really wouldn’t, unless …

          …or you want it to be type-generic? (Which may not matter in this particular case, but could more generally.)

        2. 2

          Is this a no_std project? Is that why the author isn’t using f64::powi for squaring?

          1. 4

            The author probably just hasn’t gotten there yet. They started by translating a C program line-by-line into an unsafe Rust program explaining every step along the way. As the series has progressed, it’s gotten more Rust-y but it’s still not all the way there.

            1. 2

              I asked the author via email and this was their response:

              Huh, I hadn’t considered that. The original C program wrote out x * x instead of using powi, and I followed their example.

              For what it’s worth, I put together a Criterion benchmark of the two options, and they perform equivalently on my Skylake machine (on f64). So it seems to be a matter of taste.

              Thanks for asking!

          2. 1

            Previous discussion on this same series: https://lobste.rs/s/66ozv7/learn_rust_dangerous_way