• formulaBonk ( formulaBonk@lemm.ee ) 
    link
    fedilink
    English
    arrow-up
    33
    ·
    2 years ago

    Reminds me of the days before ai assistants where people copy pasted code from forums and then you’d get quesitions like “I found this code and I know what every line does except this ‘for( int i = 0; i < 10; i ++)’ part. Is this someone using an unsupported expression?”

        • barsoap ( barsoap@lemm.ee ) 
          link
          fedilink
          arrow-up
          1
          ·
          2 years ago

          I mean i &lt; 10 isn’t wrong as such, it’s just good practice to always use &lt;= because in the INT_MAX case you have to and everything should be regular because principle of least astonishment: That 10 might become a #define FOO 10, that then might become #define FOO INT_MAX, each of those changes look valid in isolation but if there’s only a single i &lt; FOO in your codebase you introduced a bug by spooky action at a distance. (overflow on int is undefined behaviour in C, in case anyone is wondering what the bug is).

          …never believe anyone who says “C is a simple language”. Their code is shoddy and full of bugs and they should be forced to write Rust for their own good.

          • kevincox ( kevincox@lemmy.ml ) 
            link
            fedilink
            arrow-up
            5
            ·
            edit-2
            2 years ago

            But your case is wrong anyways because i &lt;= INT_MAX will always be true, by definition. By your argument &lt; is actually better because it is consistent from &lt; 0 to iterate 0 times to &lt; INT_MAX to iterate the maximum number of times. INT_MAX + 1 is the problem, not &lt; which is the standard to write for loops and the standard for a reason.

            • barsoap ( barsoap@lemm.ee ) 
              link
              fedilink
              arrow-up
              2
              ·
              2 years ago

              You’re right, that’s what I get for not having written a line of C in what 15 years. Bonus challenge: write for i in i32::MIN..=i32::MAX in C, that is, iterate over the whole range, start and end inclusive.

              (I guess the ..= might be where my confusion came from because Rust’s .. is end-exclusive and thus like &lt;, but also not what you want because i32::MAX + 1 panics).

                • barsoap ( barsoap@lemm.ee ) 
                  link
                  fedilink
                  arrow-up
                  1
                  ·
                  2 years ago

                  Would you be bold enough to write if (i++ == INT_MAX) break? The result of the increment is never used, but an increment is being done, at least syntactically, and it overflows, at least theoretically, so maybe (I’m not 100% sure) the compiler could be allowed to break out into song because undefined behaviour allows anything to happen.