The article is a bit dense, but what it's announcing is effectively golang's `defer` (with extra braces) or a limited form of C++'s RAII (with much less boilerplate).
Both RAII and `defer` have proven to be highly useful in real-world code. This seems like a good addition to the C language that I hope makes it into the standard.
Probably closer to defer in Zig than in Go, I would imagine. Defer in Go executes when the function deferred within returns; defer in Zig executes when the scope deferred within exits.
Both defer and RAII have proven to be useful, but RAII has also proven to be quite harmful in cases, in the limit introducing a lot of hidden control flow.
I think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
This certainly isn't RAII—the term is quite literal, Resource Acquisition Is Initialization, rather than calling code as the scope exits. This is the latter of course, not the former.
Though I do wonder what the chances are that the C subset of C++ will ever add this feature. I use my own homespun "scope exit" which runs a lambda in a destructor quite a bit, but every time I use it I wish I could just "defer" instead.
Various macro tricks have existed for a long time but nobody has been able to wrap the return statement yet. The lack of RAII-style automatic cleanups was one of the root causes for the legendary goto fail;[1] bug.
It’s pedantic, but in the malloc example, I’d put the defer immediately after the assignment. This makes it very obvious that the defer/free goes along with the allocation.
It would run regardless of if malloc succeeded or failed, but calling free on a NULL pointer is safe (defined to no-op in the C-spec).
It seems less pedantic and more unnecessarily dangerous due to its non uniformity: in the general case the resource won’t exist on error, and breaking the pattern for malloc adds inconsistency without any actual value gain.
Free works with NULL, but not all cleanup functions do. Instead of deciding whether to defer before or after the null check on a case-by-case basis based on whether the cleanup function handles NULL gracefully, I would just always do the defer after the null check regardless of which pair of allocation/cleanup functions I use.
It's one of the most commonly adopted feature among C successor languages (D, Zig, Odin, C3, Hare, Jai); given how opinionated some of them are on these topics, I think it's safe to say it's generally well regarded in PL communities.
It breaks the idea that statements get executed in the order they appear in the source code, but it ‘only’ moves and sometimes deduplicates (in functions with multiple exit points) statements, it doesn’t hide them.
Of course, that idea already isn’t correct in many languages; function arguments are evaluated before a function is called, operator precedence often breaks it, etc, but this moves entire statements, potentially by many lines.
I feel like C people, out of anyone, should respect the code gen wins of defer. Why would you rely on runtime conditional branches for everything you want cleaned up, when you can statically determine what cleanup functions need to be called?
In any case, the biggest advantage IMO is that resource acquisition and cleanup are next to each other. My brain understands the code better when I see "this is how the resource is acquired, this is how the resource will be freed later" next to each other, than when it sees "this is how this resource is acquired" on its own or "this is how the resource is freed" on its own. When writing, I can write the acquisition and the free at the same time in the same place, making me very unlikely to forget to free something.
It allows you to put the deferred logic near the allocation/use site which I noticed was helpful in Go as it becomes muscle memory to do cleanup as you write some new allocation and it is hinted by autocomplete these days.
But it adds a new dimension of control flow, which in a garbage collected language like Go is less worrisome whereas in C this can create new headaches in doing things in the right order. I don't think it will eliminate goto error handling for complex cases.
The advantage is that it automatically adds the cleanup code to all exit paths, so you can not forget it for some. Whether this is really that helpful is unclear to me. When we looked at defer originally for C, Robert Seacord hat a list of examples and how the looked before and after rewriting with defer. At that point I lost interest in this feature, because the new code wasn't generally better in my opinion.
But people know it from other languages, and seem to like it, so I guess it is good to have it also in C.
Confer the recent bug related to goto-error handling in OpenSSH where the "additional" error return value wasn’t caught and allowed a security bypass accepting a failed key.
Cleanup is good. Jumping around with "goto" confused most people in practice. It seems highly likely that most programmers model "defer" differently in their minds.
EDIT:
IIRC it was CVE-2025-26465. Read the code and the patch.
1. Goto pattern is very error-prone. It works until it doesn't and you have a memory leak. The way I solved this issue in my code was a macro that takes a function and creates an object that has said function in its destructor.
2. Defer is mostly useful for C++ code that needs to interact with C API because these two are fundamentally different. C API usually exposes functions "create_something" and "destroy_something", while the C++ pattern is to have an object that has "create_something" hidden inside its constructor, and "destroy_something" inside its destructor.
I’m just going to start teaching classes of C programming to university first-year CS students. Would you teach `defer` straight away to manage allocated memory?
My suggestion is no - first have them do it the hard way. This will help them build the skills to do manual memory management where defer is not available.
Once they do learn about defer they will come to appreciate it much more.
No, but also skip malloc/free until late in the year, and when it comes to heap allocation then don't use example code which allocates and frees single structs, instead introduce concepts like arena allocators to bundle many items with the same max lifetime, pool allocators with generation-counted slots and other memory managements strategies.
No. They need to understand memory failures. Teach them what it looks like when it's wrong. Then show them the tools to make things right. They'll never fully understand those tools if they don't understand the necessity of doing the right thing.
If you're teaching them to write an assembler, then it may be worth teaching them C, as a fairly basic language with a straightforward/naive mapping to assembly. But for basically any other context in which you'd be teaching first-year CS students a language, C is not an ideal language to learn as a beginner. Teaching C to first-year CS students just for the heck of it is like teaching medieval alchemy to first-year chemistry students.
The Linux kernel has been using __attribute___((cleanup)) for a little while now. So far, I've only seen/used it in cases where the alternative (one goto label) isn't very bad. Even there it's basically welcome.
But there are lots of cases in the kernel where we have 10+ goto labels for error paths in complex setup functions. I think when this starts making its way into those areas it will really start having an impact on bugs.
Sure, most of those bugs are low impact (it's rare that an attacker can trigger the broken error paths) but still, this is basically free software quality, it would be silly to leave it on the table.
And then there's the ACTUAL motivation: it makes the code look nicer.
In C I just used goto - you put a cleanup section at the bottom of your code and your error handling just jumps to it.
#define RETURN(x) result=x;goto CLEANUP
void myfunc() {
int result=0;
if (commserror()) {
RETURN(0);
}
.....
/* On success */
RETURN(1);
CLEANUP:
if (myStruct) { free(myStruct); }
...
return result
}
The advantage being that you never have to remember which things are to be freed at which particular error state. The style also avoids lots of nesting because it returns early. It's not as nice as having defer but it does help in larger functions.
This looks like a recipe for disaster when you'll free something in the return path that shouldn't be freed because it's part of the function's result, or forget to free something in a success path. Just write
result=x;
goto cleanup;
if you meant
result=x;
goto cleanup;
At least then you'll be able to follow the control flow without remembering what the magic macro does.
I have a personal aversion to defer as a language feature. Some of this is aesthetic. I prefer code to be linear, which is to say that instructions appear in the order that they are evaluated. Further, the presence of defer almost always implies that there are resources that can leak silently.
I also dislike RAII because it often makes it difficult to reason about when destructors are run and also admits accidental leaks just like defer does. Instead what I would want is essentially a linear type system in the compiler that allows one to annotate data structures that require cleanup and errors if any possible branches fail to execute the cleanup. This has the benefit of making cleanup explicit while also guaranteeing that it happens.
If you dislike things happening out of lexical order, I expect must already dislike C because of one of its many notorious footguns, which is that the evaluation order of function arguments is implementation-defined.
About RAII, I think your viewpoint is quite baffling. Destructors are run at one extremely well-defined point in the code: `}`. That's not hard to reason about at all. Especially not compared to often spaghetti-like cleanup tails. If you're lucky, the team does not have a policy against `goto`.
> I have a personal aversion to defer as a language feature.
Indeed, `defer` as a language feature is an anti-pattern.
It does not allow the abstraction of initialization/de-initialization routines and encapsulating their execution within the resources, transferring the responsibility to manually perform the release or de-initialization to the users of the resources - for each use of the resource.
> I also dislike RAII because it often makes it difficult to reason about when destructors are run [..]
RAII is a way to abstract initialization, it says nothing about where a resource is initialized.
When combined with stack allocation, now you have something that gives you precise points of construction/destruction.
The same can be said about heap allocation in some sense, though this tends to be more manual and could also involve some dynamic component (ie, a tracing collector).
> [..] and also admits accidental leaks just like defer does.
RAII is not memory management, it's an initialization discipline.
> [..] what I would want is essentially a linear type system in the compiler that allows one to annotate data structures that require cleanup and errors if any possible branches fail to execute the cleanup. This has the benefit of making cleanup explicit while also guaranteeing that it happens.
Why would you want to replicate the same cleanup procedure for a certain resource throughout the code-base, instead of abstracting it in the resource itself?
Abstraction and explicitness can co-exist. One does not rule out the other.
As others have commented already: if you want to use C++, use C++. I suspect the majority of C programmers neither care nor want stuff like this; I still stay with C89 because I know it will be portable anywhere, and complexities like this are completely at odds with the reason to use C in the first place.
I would say the complexity of implementing defer yourself is a bit annoying for C. However defer itself, as a language feature in a C standard is pretty reasonable. It’s a very straightforward concept and fits well within the scope of C, just as it fit within the scope of zig. As long as it’s the zig defer, not the golang one…
I would not introduce zig’s errdeferr though. That one would need additional semantics changes in C to express errors.
> I still stay with C89 because I know it will be portable anywhere
With respect, that sounds a bit nuts. It's been 37 years since C89; unless you're targeting computers that still have floppy drives, why give up on so many convenience features? Binary prefixes (0b), #embed, defined-width integer types, more flexibility with placing labels, static_assert for compile-time sanity checks, inline functions, declarations wherever you want, complex number support, designated initializers, countless other things that make code easier to write and to read.
Defer falls in roughly the same category. It doesn't add a whole lot of complexity, it's just a small convenience feature that doesn't add any runtime overhead.
I think a lot of the really old school people don't care, but a lot of the younger people (especially those disillusioned with C++ and not fully enamored with Rust) are in fact quite happy for C to evolve and improve in conservative, simple ways (such as this one).
You're missing out on one of the best-integrated and useful features that have been added to a language as an afterthought (C99 designated initialization). Even many moden languages (e.g. Rust, Zig, C++20) don't get close when it comes to data initialization.
Not necessarily. In classic C we often build complex state machines to handle errors - especially when there are many things that need to be initialized (malloced) one after another and each might fail. Think the infamous "goto error".
I think defer{} can simplify these flows sometimes, so it can indeed be useful for good old style C.
Defer is a very simple feature where all code is still clearly visible and nothing is called behind your back. I write a lot of C++, and it's a vastly more complex language than "C with defer". Defer is so natural to C that all compilers have relatively broadly non-standard ways of mimicking it (e.g __attribute__((cleanup)).
If you want to write C++, write C++. If you want to write C, but want resource cleanup to be a bit nicer and more standard than __attribute__((cleanup)), use C with defer. The two are not comparable.
Such addition is great. But there is something even better - destructors in C++. Anyone who writes C should consider using C++ instead, where destructors provide a more convenient way for resources freeing.
C++ destructors are implicit, while defer is explicit.
You can just look at the code in front of you to see what defer is doing. With destructors, you need to know what type you have (not always easy to tell), then find its destructor, and all the destructors of its parent classes, to work out what's going to happen.
Sure, if the situation arises frequently, it's nice to be able to design a type that "just works" in C++. But if you need to clean up reliably in just this one place, C++ destructors are a very clunky solution.
Desctructors are only comparable when you build an OnScopeExit class which calls a user-provided lambda in its destructor which then does the cleanup work - so it's more like a workaround to build a defer feature using C++ features.
The classical case of 'one destructor per class' would require to design the entire code base around classes which comes with plenty of downsides.
> Anyone who writes C should consider using C++ instead
Nah thanks, been there, done that. Switching back to C from C++ about 9 years ago was one of my better decisions in life ;)
I think destructors are different, not better. A destructor can’t automatically handle the case where something doesn’t need to be cleaned up on an early return until something else occurs. Also, destructors are a lot of boilerplate for a one-off cleanup.
For the cases where a destructor isn’t readily available, you can write a defer class that runs a lambda passed to its constructor in its destructor, can’t you?
Would be a bit clunky, but that can (¿somewhat?) be hidden in a macro, if desired.
I took some shit in the comments yesterday for suggesting "you can do it with a few lines of standard C++" to another similar thread, but yet again here we are.
Defer takes 10 lines to implement in C++. [1]
You don't have to wait 50 years for a committee to introduce basic convenience features, and you don't have to use non-portable extensions until they do (and in this case the __attribute__((cleanup)) has no equivalent in MSVC), if you use a remotely extensible language.
Why is this a relevant comment? We're talking about C, not C++. If you wanted to suggest using an alternative language, you're probably better off recommending Zig: defer takes 0 lines to implement there, and it's closer to C than what C++ is.
kjgkjhfkjf|11 days ago
Both RAII and `defer` have proven to be highly useful in real-world code. This seems like a good addition to the C language that I hope makes it into the standard.
Zambyte|11 days ago
L-4|11 days ago
I think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
throwaway27448|11 days ago
usrnm|11 days ago
omoikane|10 days ago
The extra braces appear to be optional according to the examples in https://www.open-std.org/JTC1/SC22/WG14/www/docs/n3734.pdf (see pages 13-14)
LexiMax|11 days ago
Though I do wonder what the chances are that the C subset of C++ will ever add this feature. I use my own homespun "scope exit" which runs a lambda in a destructor quite a bit, but every time I use it I wish I could just "defer" instead.
pjmlp|11 days ago
Then again, if someone is willing to push it through WG21 no matter what, maybe.
anilakar|11 days ago
[1] https://gotofail.com/
surajrmal|11 days ago
mwkaufma|10 days ago
jonhohle|11 days ago
It would run regardless of if malloc succeeded or failed, but calling free on a NULL pointer is safe (defined to no-op in the C-spec).
flakes|11 days ago
free may accept a NULL pointer, but it also doesn't need to be called with one either.
masklinn|11 days ago
mort96|11 days ago
krautsauer|11 days ago
unknown|11 days ago
[deleted]
babalark|11 days ago
Related blog post from last year: https://thephd.dev/c2y-the-defer-technical-specification-its... (https://news.ycombinator.com/item?id=43379265)
joexbayer|11 days ago
https://oshub.org/projects/retros-32/posts/defer-resource-cl...
cmovq|11 days ago
fuhsnn|11 days ago
Someone|11 days ago
Of course, that idea already isn’t correct in many languages; function arguments are evaluated before a function is called, operator precedence often breaks it, etc, but this moves entire statements, potentially by many lines.
kibwen|10 days ago
jrmg|10 days ago
ozgrakkurt|11 days ago
Genuinely curious as I only have a small amount of experience with c and found goto to be ok so far
mort96|11 days ago
In any case, the biggest advantage IMO is that resource acquisition and cleanup are next to each other. My brain understands the code better when I see "this is how the resource is acquired, this is how the resource will be freed later" next to each other, than when it sees "this is how this resource is acquired" on its own or "this is how the resource is freed" on its own. When writing, I can write the acquisition and the free at the same time in the same place, making me very unlikely to forget to free something.
kev009|11 days ago
But it adds a new dimension of control flow, which in a garbage collected language like Go is less worrisome whereas in C this can create new headaches in doing things in the right order. I don't think it will eliminate goto error handling for complex cases.
uecker|11 days ago
But people know it from other languages, and seem to like it, so I guess it is good to have it also in C.
dapperdrake|11 days ago
Cleanup is good. Jumping around with "goto" confused most people in practice. It seems highly likely that most programmers model "defer" differently in their minds.
EDIT:
IIRC it was CVE-2025-26465. Read the code and the patch.
anal_reactor|11 days ago
2. Defer is mostly useful for C++ code that needs to interact with C API because these two are fundamentally different. C API usually exposes functions "create_something" and "destroy_something", while the C++ pattern is to have an object that has "create_something" hidden inside its constructor, and "destroy_something" inside its destructor.
gignico|11 days ago
zffr|11 days ago
Once they do learn about defer they will come to appreciate it much more.
orlp|11 days ago
The point of a CS degree is to know the fundamentals of computing, not the latest best practices in programming that abstract the fundamentals.
leni536|11 days ago
flohofwoe|11 days ago
junon|11 days ago
uecker|11 days ago
dapperdrake|10 days ago
kibwen|11 days ago
bjackman|11 days ago
But there are lots of cases in the kernel where we have 10+ goto labels for error paths in complex setup functions. I think when this starts making its way into those areas it will really start having an impact on bugs.
Sure, most of those bugs are low impact (it's rare that an attacker can trigger the broken error paths) but still, this is basically free software quality, it would be silly to leave it on the table.
And then there's the ACTUAL motivation: it makes the code look nicer.
t43562|11 days ago
vasama|11 days ago
You also don't have to remember this when using defer. That's the point of defer - fire and forget.
vbezhenar|11 days ago
baq|11 days ago
Joker_vD|10 days ago
pocksuppet|11 days ago
bytejanitor|11 days ago
norir|10 days ago
I also dislike RAII because it often makes it difficult to reason about when destructors are run and also admits accidental leaks just like defer does. Instead what I would want is essentially a linear type system in the compiler that allows one to annotate data structures that require cleanup and errors if any possible branches fail to execute the cleanup. This has the benefit of making cleanup explicit while also guaranteeing that it happens.
simonask|10 days ago
About RAII, I think your viewpoint is quite baffling. Destructors are run at one extremely well-defined point in the code: `}`. That's not hard to reason about at all. Especially not compared to often spaghetti-like cleanup tails. If you're lucky, the team does not have a policy against `goto`.
ameixaseca|10 days ago
Indeed, `defer` as a language feature is an anti-pattern.
It does not allow the abstraction of initialization/de-initialization routines and encapsulating their execution within the resources, transferring the responsibility to manually perform the release or de-initialization to the users of the resources - for each use of the resource.
> I also dislike RAII because it often makes it difficult to reason about when destructors are run [..]
RAII is a way to abstract initialization, it says nothing about where a resource is initialized.
When combined with stack allocation, now you have something that gives you precise points of construction/destruction.
The same can be said about heap allocation in some sense, though this tends to be more manual and could also involve some dynamic component (ie, a tracing collector).
> [..] and also admits accidental leaks just like defer does.
RAII is not memory management, it's an initialization discipline.
> [..] what I would want is essentially a linear type system in the compiler that allows one to annotate data structures that require cleanup and errors if any possible branches fail to execute the cleanup. This has the benefit of making cleanup explicit while also guaranteeing that it happens.
Why would you want to replicate the same cleanup procedure for a certain resource throughout the code-base, instead of abstracting it in the resource itself?
Abstraction and explicitness can co-exist. One does not rule out the other.
dapperdrake|10 days ago
userbinator|11 days ago
laserbeam|11 days ago
I would not introduce zig’s errdeferr though. That one would need additional semantics changes in C to express errors.
lich_king|11 days ago
With respect, that sounds a bit nuts. It's been 37 years since C89; unless you're targeting computers that still have floppy drives, why give up on so many convenience features? Binary prefixes (0b), #embed, defined-width integer types, more flexibility with placing labels, static_assert for compile-time sanity checks, inline functions, declarations wherever you want, complex number support, designated initializers, countless other things that make code easier to write and to read.
Defer falls in roughly the same category. It doesn't add a whole lot of complexity, it's just a small convenience feature that doesn't add any runtime overhead.
Mond_|11 days ago
flohofwoe|11 days ago
You're missing out on one of the best-integrated and useful features that have been added to a language as an afterthought (C99 designated initialization). Even many moden languages (e.g. Rust, Zig, C++20) don't get close when it comes to data initialization.
majke|11 days ago
I think defer{} can simplify these flows sometimes, so it can indeed be useful for good old style C.
rwmj|11 days ago
mort96|11 days ago
If you want to write C++, write C++. If you want to write C, but want resource cleanup to be a bit nicer and more standard than __attribute__((cleanup)), use C with defer. The two are not comparable.
ozgrakkurt|11 days ago
Goto approach also covers some more complicated cases
pjmlp|11 days ago
sp1rit|11 days ago
avadodin|11 days ago
If you can't compile K&R, you should label your language "I can't believe it's not C!".
I don't have time to learn your esolang.
Panzerschrek|11 days ago
alextingle|11 days ago
You can just look at the code in front of you to see what defer is doing. With destructors, you need to know what type you have (not always easy to tell), then find its destructor, and all the destructors of its parent classes, to work out what's going to happen.
Sure, if the situation arises frequently, it's nice to be able to design a type that "just works" in C++. But if you need to clean up reliably in just this one place, C++ destructors are a very clunky solution.
flohofwoe|11 days ago
The classical case of 'one destructor per class' would require to design the entire code base around classes which comes with plenty of downsides.
> Anyone who writes C should consider using C++ instead
Nah thanks, been there, done that. Switching back to C from C++ about 9 years ago was one of my better decisions in life ;)
amluto|11 days ago
mathisfun123|11 days ago
Someone|11 days ago
Would be a bit clunky, but that can (¿somewhat?) be hidden in a macro, if desired.
clarabennett26|10 days ago
[deleted]
unit149|11 days ago
[deleted]
nananana9|11 days ago
Defer takes 10 lines to implement in C++. [1]
You don't have to wait 50 years for a committee to introduce basic convenience features, and you don't have to use non-portable extensions until they do (and in this case the __attribute__((cleanup)) has no equivalent in MSVC), if you use a remotely extensible language.
[1] https://www.gingerbill.org/article/2015/08/19/defer-in-cpp/
mort96|11 days ago