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.
Sometimes we need block scoped cleanup, other times we need the function one.
You can turn the function scoped defer into a block scoped defer in a function literal.
AFAICT, you cannot turn a block scoped defer into the function one.
So I think the choice was obvious - go with the more general(izable) variant. Picking the alternative, which can do only half of the job, would be IMO a mistake.
I hate even more that you can call defer in a loop, and it will appear to work, as long as the loop has relatively few iterations, and is just silently massively wasteful.
By the way, GCC and Clang have attribute((cleanup)) (which is the same, scope-based clean-up) and have done for over a decade, and this is widely used in open source projects now.
In Golang if you iterate over a thousand files and
defer File.close()
your OS will run out of file descriptorsI think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
It allows library authors to take responsibility for cleaning up resources in exactly one place rather than forcing library users to insert a defer call in every single place the library is used.
But yeah, RAII can only provide deterministic destruction because resource acquisition is initialization. As long as resource acquisition is decoupled from initialization, you need to manually track whether a variable has been initialized or not, and make sure to only call a destruction function (be that by putting free() before a return or through 'defer my_type_destroy(my_var)') in the paths where you know that your variable is initialized.
So "A limited form of RAII" is probably the wrong way to think about it.
It's not uncommon that I encounter a bug when running some code on new hardware or a new architecture or a new compiler for the first time because the code assumed that an integer member of a class would be 0 right after initialization and that happened to be true before. ASan helps here, but it's not trivial to run in all embedded contexts (and it's completely out of the question on MCUs).
Anyway, I think this could be fixed, if we wanted to. C just describes the objects as being uninitialized and has a bunch of UB around uninitialized objects. Nothing in C says that an implementation can't make every uninitialized object 0. As such, it would not harm C interoperability if C++ just declared that all variable declarations initialize variables to their zero value unless the declaration initializes it to something else.
Which removes half the value of RAII as I see it—needing when and to know how to unacquire the resource is half the battle, a burden that using RAII removes.
Of course, calling code as the scope exits is still useful. It just seems silly to call it any form of RAII.
I got out my 4e Stroustrup book and checked the index, RAII only comes up when discussing resource management.
Interestingly, the verbatim introduction to RAII given is:
> ... RAII allows us to eliminate "naked new operations," that is, to avoid allocations in general code and keep them buried inside the implementation of well-behaved abstractions. Similarly "naked delete" operations should be avoided. Avoiding naked new and naked delete makes code far less error-prone and far easier to keep free of resource leaks
From the embedded standpoint, and after working with Zig a bit, I'm not convinced about that last line. Hiding heap allocations seems like it make it harder to avoid resource leaks!
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.
Then again, if someone is willing to push it through WG21 no matter what, maybe.
C++ would be a nicer language with native defer. Working directly with C APIs (which is one of the main reasons to use C++ over Rust or Zig these days) would greatly benefit from it.
Working with native C APIs in C++ is akin to using unsafe in Rust, C#, Swift..., it should be wrapped in type safe functions or classes/structs, never used directly outside implementation code.
If folks actually followed this more often, there would be so much less CVE reports in C++ code caused by calling into C.
If I'm constructing a particular C object once in my entire code base, calling a couple functions on it, then freeing it, I'm not much more likely to get it right in the RAII wrapper than in the one place in my code base I do it manually. At least if I have tools like defer to help me.
I'm assuming that using defer would have prevented the gotos in the first case, and the bug.
C is hard enough as is to get right and every tool and development pattern that helps avoid common pitfalls is welcome.
By putting all the cleanup code at the end of the function after a cleanup label, you have reduced the complexity of resource management: you have one place where the resource is acquired, and one place where the resource is freed. This is actually manageable. Before you return, you check every resource you might have acquired, and if your handle (pointer, file descriptor, PID, whatever) is not in its null state (null pointer, -1, whatever), you call the free function.
By comparison, if you try to put the correct cleanup functions at every exit point, the problem explodes in complexity. Whereas correctly adding a new resource using the 'goto cleanup' pattern requires adding a single 'if (my_resource is not its null value) { cleanup(my_resource) }' at the end of the function, correctly adding a new resource using the 'cleanup at every exit point' pattern requires going through every single exit point in the function, considering whether or not the resource will be acquired at that time, and if it is, adding the cleanup code. Adding a new exit point similarly requires going through all resources used by the function and determining which ones need to be cleaned up.
C is hard enough as it is to get right when you only need to remember to clean up resources in one place. It gets infinitely harder when you need to match up cleanup code with returns.
Using defer, the code would be:
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
return err;
return err;
This has the exact same bug: the function exits with a successful return code as long as the SHA hash update succeeds, skipping further certificate validity checks. The fact that resource cleanup has been relegated to defer so that 'goto fail;' can be replaced with 'return err;' fixes nothing.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).
resource, err := newResource()
if err != nil {
return err
}
defer resource.Close()
IMO this pattern makes more sense, as calling exit behavior in most cases won't make sense unless you have acquired the resource in the first place.free may accept a NULL pointer, but it also doesn't need to be called with one either.
RAII is not the right solution for C. I wouldn't want C to grow constructors and destructors. So far, C only runs the code you ask it to; turning variable declaration into a hidden magic constructor call would, IMO, fly in the face of why people may choose C in the first place.
In addition, RAII has it's own complexities that need to be dealt with now, i.e. move semantics, which obviously C does not have nor will it likely ever.
In the example above, the question of "do I put defer before or after the `if err != nil` check" is deferred to the programmer. RAII forces you to handle the complexity, defer lets you shoot yourself in the foot.
#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.You also don't have to remember this when using defer. That's the point of defer - fire and forget.
There are several other issues I haven't shown like what happens if you need to free something only when the return code is "FALSE" indicating that something failed.
This is not as nice as defer but up till now it was a comparatively nice way to deal with those functions which were really large and complicated and had many exit points.
In other words, the first time you access a "freshly allocated" non-null pointer you may get a page fault due to insufficient physical memory.
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.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.
Genuinely curious as I only have a small amount of experience with c and found goto to be ok so far
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.
Lovely fairy tale. Now can you tell me how you love to scroll back and examine all the defer blocks within a scope when it ends to understand what happens at that point?
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.
But people know it from other languages, and seem to like it, so I guess it is good to have it also in C.
http://robertseacord.com/wp/2020/09/10/adding-a-defer-mechan...
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.
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.
For example if I have a ffi function that transfers the ownership of some allocator in the middle of the function.
https://oshub.org/projects/retros-32/posts/defer-resource-cl...
Related blog post from last year: https://thephd.dev/c2y-the-defer-technical-specification-its... (https://news.ycombinator.com/item?id=43379265)
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.
Once they do learn about defer they will come to appreciate it much more.
The point of a CS degree is to know the fundamentals of computing, not the latest best practices in programming that abstract the fundamentals.
learning Python first is same difficulty as learning C first (because main problem is the whole concept of programming)
and learning C after Python is harder than learning Python after C (because of pointers)
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.
> 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
Isn't it a code quality issue? It should be clear from class name/description what can happen in its destructor. And if it's not clear, it's not that relevant.
It's absolutely a problem. Classically, you spend most of your time reading and debugging code, not writing it. When there's an issue pertaining to RAII, it is hidden away, potentially requiring looking at many subclasses etc.
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 ;)
It can. An object with destructor doing clean-up should be created only after such clean-up is needed. In case of a file, for example, a file object should be created at file opening, so that it can close the file in its destructor.
The decision would be easier if the C subset in C++ would be compatible with modern C standards instead of being a non-standard dialect of C stuck in ca. 1995.
Would be a bit clunky, but that can (¿somewhat?) be hidden in a macro, if desired.
I would not introduce zig’s errdeferr though. That one would need additional semantics changes in C to express errors.
It starts out small. Then before you know the language is total shit. Python is a good example.
I am observing a very distinguishable phenomenon when internet makes very shallow ideas mainstream and ruin many many good things that stood the test of time.
I am not saying this is one of those instances, but what the parent comment makes sense to me. You can see another comment who now wants to go further and want destructors in C. Because of internet, such voices can now reach out to each other, gather and cause a change. But before, such voices would have to go through a lot of sensible heads before they would be able to reach each other. In other words, bad ideas got snuffed early before internet, but now they go mainstream easily.
So you see, it starts out slow, but then more and more stuff gets added which diverges more and more from the point.
Actually I am not sure I do. It seems to me that even though `defer` is more explicit than destructors, it still falls under "spooky action at a distance" category.
The former would be bring so much in C that it wouldn't be C anymore.
And if your point is "you should switch to C++ to get destructors", then it seems out of topic. By very definition, if we're talking about language X and your answer is "switch to Y", this is an entirely different subject, of very few interest to people programming in X.
But the point is `defer` is still in "spooky action at a distance" category that I generally don't want in programming languages, especially in c.
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.
The one huge advantage of C is its ubiquity - you can use it on the latest shiny computer / OS / compiler as well as some obscure embedded platform with a compiler that hasn't been updated since 2002. (That's a rare enough situation to be unimportant, right? /laughs in industrial control gear.)
I'm wary of anything which fragments the language and makes it inaccessible to subsections of its traditional strongholds.
While I'm not a huge fan of the "just use Rust" attitude that crops up so often these days, you could certainly make an argument that if you want modern language features you should be using a more modern language.
(And, for the record, I do still write software - albeit recreationally - for computers that have floppy drives.)
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.
E.g. neither Rust, Zig nor C++20 can do this:
https://github.com/floooh/sokol-samples/blob/51f5a694f614253...
Odin gets really close but can't chain initializers (which is ok though):
https://github.com/floooh/sokol-odin/blob/d0c98fff9631946c11...
As far as I can tell, Rust can do what it is in your example (which different syntax of course) except for this particular way of initializing an array.
To me, that seems like a pretty minor syntax issue to that could be added to Rust if there would be a lot of demand for initializing arrays this way.
E.g. notice how here in Rust each nested struct needs a type annotation, even though the compiler could trivially infer the type. Rust also cannot initialize arrays with random access directly, it needs to go through an expression block. Finally Rust requires `..Default::default()`:
https://github.com/floooh/sokol-rust/blob/f824cd740d2ac96691...
Zig has most of the same issues as Rust, but at least the compiler is able to infer the nested struct types via `.{ }`:
https://github.com/floooh/sokol-zig/blob/17beeab59a64b12c307...
I don't have C++ code around, but compared to C99 it has the following restrictions:
- designators must appear in order (a no-go for any non-trivial struct)
- cannot chain designators (e.g. `.a.b.c = 123`)
- doesn't have the random array access syntax via `[index]`
> ...like a pretty minor syntax issue...
...sure, each language only has a handful minor syntax issues, but these papercuts add up to a lot of syntax noise to sift through when compared to the equivalent C99 code.
I have to admit, the ..Default::default() syntax is pretty ugly.
In theory Rust could do "let x: Foo = _ { field }" and "Foo { field: _ { bar: 1 } }". That doesn't even change the syntax. Its just whether enough people care.
I think defer{} can simplify these flows sometimes, so it can indeed be useful for good old style C.
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.
Goto approach also covers some more complicated cases
Is that supposed to exacerbate how poor that choice is. External assembly is great.
Even today, the only usable Assemblers on UNIX platforms were born in PC or Amiga.
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.
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/
My comment is targeted towards the programmer who is excited about features like this - you can add an extra two characters to your filename and trivially implement those improvements (and more) yourself, without any alterations to your codebase or day to day programming style.
C++ doesn't let you implicitly cast from void* to other pointer types. This breaks the way you typically heap-allocate variables in C: instead of 'mytype *foo = malloc(sizeof(*foo))', you have to write 'mytype *foo = (mytype *)malloc(sizeof(*foo))'. This adds a non-trivial amount of friction to something you do every handful of lines.
String literals in C++ are 'const char *' instead of 'char *'. While this is more technically correct, it means you have to add casts to 'char *' all over the place. Plenty of C APIs are really not very ergonomic when string literals aren't 'char *'.
And the big one: C++ doesn't have C's struct literals. Lots of C APIs are super ergonomic if you call them like this:
some_function(&(struct params) {
.some_param = 10,
.other_param = 20,
});
You can't do that in C++. C++ has other features (such as its own, different kind of aggregate initialization with designated initializers, and the ability for temporaries to be treated as const references) which make C++ APIs nice to work with from C++, but C APIs based around the assumption that you'll be using struct literals aren't nice to use from C++.If you wanna use C, use C. C is a much better C than C++ is.
I like both these syntax-es (syntacies? synticies?) and I hope they make their way to C++, but if we're honestly evaluating features -- take their utility, multiply it by 100 and in my book it's still losing out against either defer or slices/span types.
If you disagree with this, then your calculus for feature utility is completely different than mine. I suspect for most people that's not the case, and most of the time the reason to pick C over C++ is ideological, not because of these 2 pieces of syntax sugar.
"I like it" is a good enough reason to use something, my original comment is to the person who wants to use C but gets excited about features like this - I don't know how many of those people are aware of how trivially most of these things can be accomplished in C++.