Iterating Backwards in C

(davidpriver.com)

19 points | by cremno 3 days ago

4 comments

  • kenferry 32 minutes ago
    I know it's "too clever", but if I'm writing code no one else will ever see,

      while (i --> 0) {
          // use array[i]
      }
    
    easy to read (if not understand), and correct!
    • viega 17 minutes ago
      I always use unsigned values and do:

        while (i-- != 0) { ... }
      
      It's more clear than the most idiomatic way, which is to drop the explicit comparison:

        while (i--) { ... }
       
      All of it is better than the clunky old for-loop syntax.
    • krackers 25 minutes ago
      Oh I remember this from the classic SO post, but it was just presented as a funny trick. I never realized that it solves the issue mentioned in the article and there is a legitimate use-case for post-decrement in the comparison itself.

      https://stackoverflow.com/questions/1642028/what-is-the-oper...

    • stephencanon 30 minutes ago
      Always.

      (Hi Ken!)

  • MaulingMonkey 49 minutes ago
    I prefer:

        const size_t n = 10;
        for (size_t i = n; i --> 0;) {
            std::cout << i << "\n";
        }
    • hedgehog 40 minutes ago
      That's a certain kind of taste... I checked out your home page, game dev, check, and this work of art is worth linking (no irony, I love it):

      http://maulingmonkey.com/brainfuck/

    • ranger_danger 40 minutes ago
      Cute but wouldn't work with ssize_t :)

      VHDL's array/vector syntax actually works a similar way:

      -- gives 0, 1, 2, 3:

      for i in 0 to 3 loop

      -- gives 3, 2, 1, 0:

      for i in 3 downto 0 loop

      -- Source - https://stackoverflow.com/a/7642026 -- Posted by Kerrek SB -- Retrieved 2026-10-29, License - CC BY-SA 3.0

      • fourthark 13 minutes ago
        Does work with ssize_t, just not necessary.
  • abstractspoon 2 days ago
    I've been using this method for more than 30 years!
  • rpsworld 53 minutes ago
    [flagged]