upvote
I think defer has been included in the next round of working group proposals for C2y, but I don't think Apple's clang has it. Maybe it's there as a language extension and I just didn't see it.

What lib0xc has is some cleanup attributes that you can apply to variables to e.g. automatically free a heap allocation or close a file descriptor, at end of scope. Personally, I like variable annotations much more than defer for these uses, but they accomplish the same thing. I've also found that using those attributes inherently pushes your code to make ownership more explicit. I personally stopped being terrified of double-pointers and started using them for ownership transfers, which eliminates a large class of bugs.

reply
> I've also found that using those attributes inherently pushes your code to make ownership more explicit. I personally stopped being terrified of double-pointers and started using them for ownership transfers, which eliminates a large class of bugs.

This is very interesting. Do you have a practical example?

reply
In C++ you can implement such a thing using destructors, which are guaranteed to run in reverse order on scope exit even in the presence of exceptions. Alexei Alexandrescu's Scopeguard did this (in the 90s I think, long before C++11). But in standard C, there's no mechanism that this could be attached to (especially if you want to use "C exceptions", a.k.a. setjmp()/longjmp()).

Maybe the compilers they support all have non-standard extensions that allow something like this though?

reply
Yes, because all compilers support a non-standard defer mechanism, its now being considered for inclusion into standard C. [0]

And that suggested defer standard, is already available from GCC 9 and clang 22.

[0] https://www.open-std.org/JTC1/SC22/WG14/www/docs/n3734.pdf

reply
[flagged]
reply