{"article":{"slug":"iterating-backwards-in-c","title":"Iterating Backwards in C","subtitle":null,"summary":"David Priver shows the simple, correct way to loop backwards over a buffer with an unsigned size_t counter in C, avoiding signed-index conversions and off-by-one bugs he says he keeps seeing, even more so in LLM-written code.","content_type":"tutorial","language":"en","canonical_url":"https://www.davidpriver.com/Iterating-backwards-in-C.html","author":{"name":"David Priver","url":"https://www.davidpriver.com/","person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"David Priver","url":"https://www.davidpriver.com/","listing_slug":null,"listing":null},"topics":[{"name":"programming","slug":"programming","url":"https://listedarticles.com/topics/programming"},{"name":"c","slug":"c","url":"https://listedarticles.com/topics/c"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":444,"reading_minutes":2,"published_at":"2026-10-30T02:07:51.637Z","added_at":"2026-10-30T02:07:51.637Z","updated_at":"2026-10-30T02:07:51.637Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/iterating-backwards-in-c","markdown_url":"https://listedarticles.com/articles/iterating-backwards-in-c.md","example":false,"citation":"David Priver, David Priver. \"Iterating Backwards in C.\" 30 Oct 2026. https://www.davidpriver.com/Iterating-backwards-in-C.html (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://www.davidpriver.com/Iterating-backwards-in-C.html"},"body_markdown":"# Iterating Backwards in C\n\nThis is shorter than some of my other posts, but I keep seeing people\ndoing this wrong. It's even worse now in the LLM era.\n\nLet's say you have a buffer and a counter and you need to iterate it\nbackwards for some reason:\n\n```\n_Bool find_last(size_t count, int *haystack,\n                int needle, size_t *where);\n```\n\nAlmost everyone can do the forward version on autopilot:\n\n```\nfor(size_t i = 0; i < count; i++){\n  if(haystack[i] == needle){\n    *where = i;\n    return 1;\n  }\n}\nreturn 0;\n```\n\nSo they try to do the same thing, just iterating backwards:\n\n```\nfor(size_t i = count - 1; i >= 0; i--){\n  // find needle\n}\n```\n\nBut that doesn't work at all! i >=0 is tautologically true\n(modern compilers will warn). Even worse, if count is 0, i immediately becomes\nSIZE\\_MAX.\n\nOk, so they try the next version:\n\n```\nfor(ssize_t i = count - 1; i >= 0; i--){\n  // find needle\n}\n```\n\nThis works in practice with a signed index but introduces\nsome problems:\n\n- Now your index variable is signed, which can cause problems when used in expressions due to\n  C's conversion rules.\n- ssize\\_t is a POSIX thing so you'd have to define it yourself on windows.\n- If your type is 32 bit, you run into promotion problems and might even run into truncation problems.\n- This spelling of the loop is overcomplicated and requires special inspection\n  each time. Did you get the second-clause condition right?\n\nAvoiding these problems brings us to the actual, proper way to iterate backwards in C:\n\n```\nfor(size_t i = count; i--; ){\n  // find needle\n}\n```\n\nSo much simpler! Let's break it down:\nThe key is the postdecrement operator on i.\nIt decrements i but yields the value that i was before the operation.\nIn this case, this means that in the body of the loop i is always in bounds\nas its value will be decremented after initialization so it is at most count - 1,\nwhile the condition checks that if it was previously 0 then the loop ends. i will\nwrap around, but unsigned wrap-around is well defined in C so that is not a problem.\n\nThe final version:\n\n```\n_Bool find_last(size_t count, int *haystack,\n                int needle, size_t *where){\n  for(size_t i = count; i--; ){\n    if(haystack[i] == needle){\n      *where = i;\n      return 1;\n    }\n  }\n  return 0;\n}\n```\n\nDoing it this way means you don't have to mess around with converting to a signed\nloop index and look at how simple that loop is! You can tell at a glance\nif someone has implemented the reverse loop properly or not.\n\nSo please! If you see someone trying to iterate backwards, show them this way\nto do it!\n","body_html":"<h1 id=\"iterating-backwards-in-c\">Iterating Backwards in C</h1>\n<p>This is shorter than some of my other posts, but I keep seeing people\ndoing this wrong. It&#39;s even worse now in the LLM era.</p>\n<p>Let&#39;s say you have a buffer and a counter and you need to iterate it\nbackwards for some reason:</p>\n<pre><code>_Bool find_last(size_t count, int *haystack,\n                int needle, size_t *where);</code></pre>\n<p>Almost everyone can do the forward version on autopilot:</p>\n<pre><code>for(size_t i = 0; i &lt; count; i++){\n  if(haystack[i] == needle){\n    *where = i;\n    return 1;\n  }\n}\nreturn 0;</code></pre>\n<p>So they try to do the same thing, just iterating backwards:</p>\n<pre><code>for(size_t i = count - 1; i &gt;= 0; i--){\n  // find needle\n}</code></pre>\n<p>But that doesn&#39;t work at all! i &gt;=0 is tautologically true\n(modern compilers will warn). Even worse, if count is 0, i immediately becomes\nSIZE_MAX.</p>\n<p>Ok, so they try the next version:</p>\n<pre><code>for(ssize_t i = count - 1; i &gt;= 0; i--){\n  // find needle\n}</code></pre>\n<p>This works in practice with a signed index but introduces\nsome problems:</p>\n<ul><li><p>Now your index variable is signed, which can cause problems when used in expressions due to</p><p>C&#39;s conversion rules.</p></li><li>ssize_t is a POSIX thing so you&#39;d have to define it yourself on windows.</li><li>If your type is 32 bit, you run into promotion problems and might even run into truncation problems.</li><li><p>This spelling of the loop is overcomplicated and requires special inspection</p><p>each time. Did you get the second-clause condition right?</p></li></ul>\n<p>Avoiding these problems brings us to the actual, proper way to iterate backwards in C:</p>\n<pre><code>for(size_t i = count; i--; ){\n  // find needle\n}</code></pre>\n<p>So much simpler! Let&#39;s break it down:\nThe key is the postdecrement operator on i.\nIt decrements i but yields the value that i was before the operation.\nIn this case, this means that in the body of the loop i is always in bounds\nas its value will be decremented after initialization so it is at most count - 1,\nwhile the condition checks that if it was previously 0 then the loop ends. i will\nwrap around, but unsigned wrap-around is well defined in C so that is not a problem.</p>\n<p>The final version:</p>\n<pre><code>_Bool find_last(size_t count, int *haystack,\n                int needle, size_t *where){\n  for(size_t i = count; i--; ){\n    if(haystack[i] == needle){\n      *where = i;\n      return 1;\n    }\n  }\n  return 0;\n}</code></pre>\n<p>Doing it this way means you don&#39;t have to mess around with converting to a signed\nloop index and look at how simple that loop is! You can tell at a glance\nif someone has implemented the reverse loop properly or not.</p>\n<p>So please! If you see someone trying to iterate backwards, show them this way\nto do it!</p>","headings":[{"level":1,"text":"Iterating Backwards in C","id":"iterating-backwards-in-c"}]}}