Sujet : Re: Opinions on `defer`?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 08. Jan 2025, 02:02:05
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250107162317.431@kylheku.com>
References : 1 2
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-01-08, Janis Papanagnou <janis_papanagnou+
ng@hotmail.com> wrote:
On 07.01.2025 01:35, Alexis wrote:
Hi all,
"Modern C" author Jens Gustedt has been posting on his blog about a
proposed `defer` feature (as provided by e.g. Zig and Go), the most
recent being:
https://gustedt.wordpress.com/2025/01/06/simple-defer-ready-to-use/
What do people here think about having such a feature in C?
>
(For C++, as the author also intended, it seems, IME, to not make much
sense.) For "C", inspecting the samples on that page, the most obvious
application case seems to me to be the heap allocations; there I first
had the question of how it would behave e.g. with 'realloc's. But more
importantly, it doesn't seem to match my typical applications of heap
allocations, which I regularly don't do with just a block scope - on
If you do anything like this:
FILE *f = fopen(...);
if (f) {
/* read file */
fclose(f);
} else {
/* error */
}
you have heap allocation in a block scope discipline. You can't make
that a stack allocation, because there is no such thing as this:
FILE fobj;
FILE *f = fopen_fobj(&fobj, ...);
and even if there were such a thing, you'd still need to call a
destructor similar to fclose it to close the file descriptor inside
fobj and free any dynamic buffers!
Defer could be used to help manage home-grown exception handling.
In home-grown exception handling schemes, you push your own unwind
info. This is hidden by macros:
{
unwind_frame_t uf;
exception_push_frame(&uf);
...
exception_pop_frame(&uf);
}
If you leave that scope, forgetting to pop, it's a big problem.
A defer mechanism could help with that.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca