HNHacker News
TopNewBestAskShowJobs

taeber

23 karma · joined May 29, 2020

https://github.com/taeber

God bless you!

submissionscomments
taeber··on A simple defer feature for C
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

taeber··on A simple defer feature for C
I like the idea of automatic resource cleanup in C and was excited when I read the headline, but I agree with others that the proposed syntax doesn't seem very C-like.

I previously shared a "with" statement idea on HN that I thought fit with the rest of the language.

  with (FILE *fp; fp = fopen(path, "wb"); fclose(fp)) {
  ...
  } else {
    perror("Failed to open file");
  }
https://github.com/taeber/cwith

https://news.ycombinator.com/item?id=23370693

edit: formatting

taeber··on Show HN: Automatic cleanup in C using with-statements
Yes you can. I did mention GCC's cleanup attribute along with MSVC's try-finally construct. Another user was kind enough to even provide an example in their GitHub issue: https://github.com/taeber/cwith/issues/1.
taeber··on Show HN: Automatic cleanup in C using with-statements
Thank you! I'd much prefer to not have to use macros, but I tried to make the with/withif mimic what I wish was a real C statement.