Doing something n times in C with while and decrement

Here’s the standard way to do_something() n times in C:

for (int i = 0; i < n; i++) {
  do_something();
}

But if you don’t use n after the loop, and you don’t use i in the loop body, this is a simpler way:


while (n--) {
  do_something();
}

Full example:

#include <stdio.h>
int main(void) {
  int n = 3;
  while (n--) {
    printf("hey\n");
  }
  return 0;
}

which prints:

% ./a.out
hey
hey
hey
👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business?Read more about me or Get in touch!

More by Jim

Tagged #c, #programming. All content copyright James Fisher 2017. This post is not associated with my employer.Found an error? Edit this page.