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 just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

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