Hacker News new | ask | show | jobs
by taeber 1619 days ago
I'm glad you suggested that, because one of the first comparisons I drew in my article[1] about the "with"-syntax was how it looks like a for-loop.

If you are interested, I did provide a few macros[2], but as another commenter pointed out, they won't handle an early return. You can use "break" to exit early though:

  #define with(declare, startup, cleanup, block) \
      {                      \
          declare;           \
          if (( startup )) { \
              do {           \
                  block;     \
              } while(0);    \
              cleanup;       \
          }                  \
      }

  with (FILE *fp, fp = fopen(path, "rb"), fclose(fp), {
    fread(buf, 1, sizeof(buf)-1, fp);
    if (ferror(fp)) {
      perror(path);
      break;
    }
    printf("%s\n", buf);
    success = 1;
  })
There's also "withif"

  #define withif(declare, startup, cleanup, block, otherwise) \
      {                      \
          declare;           \
          if (( startup )) { \
              do {           \
                  block;     \
              } while(0);    \
              cleanup;       \
          } otherwise;       \
      }
[1]https://github.com/taeber/cwith

[2]https://github.com/taeber/cwith/blob/master/with.h