A long overdue feature.

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.

In many cases that's preferred as you want the ability to cancel the deferred lambda.
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.

  • L-4
  • ·
  • 12 minutes ago
  • ·
  • [ - ]
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.

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.
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).

  • flakes
  • ·
  • 34 minutes ago
  • ·
  • [ - ]
I'd say a lot of users are going to borrow patterns from Go, where you'd typically check the error first.

    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.

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.
  • ·
  • 1 hour ago
  • ·
  • [ - ]
  • cmovq
  • ·
  • 34 minutes ago
  • ·
  • [ - ]
Would defer be considered hidden control flow? I guess it’s not so hidden since it’s within the same function unlike destructors, exceptions, longjmp.
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?
  • kibwen
  • ·
  • 32 minutes ago
  • ·
  • [ - ]
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.
I think I heard this in some cppcon video, from uni teacher who had to make students know both C and Python, so he experimented for several years

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)

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.
It's still only in a TS, not in ISO C, if that matters.
  • orlp
  • ·
  • 34 minutes ago
  • ·
  • [ - ]
In university? No, absolutely not straight away.

The point of a CS degree is to know the fundamentals of computing, not the latest best practices in programming that abstract the fundamentals.

  • jurf
  • ·
  • 20 minutes ago
  • ·
  • [ - ]
My university also taught best practices alongside that, everytime. I am very grateful for that.
  • zffr
  • ·
  • 42 minutes ago
  • ·
  • [ - ]
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.

  • uecker
  • ·
  • 28 minutes ago
  • ·
  • [ - ]
IMHO, it is in the best interest of your students to teach them standard C first.
  • thayne
  • ·
  • 10 minutes ago
  • ·
  • [ - ]
There is a technical specification, so hopefully it will be standard C in the next version. And given that gcc and clang already have implementatians (and gcc has had a way to do it for a long time, although the syntax is quite different).
Yes!! One step closer to having defer in the standard.

Related blog post from last year: https://thephd.dev/c2y-the-defer-technical-specification-its... (https://news.ycombinator.com/item?id=43379265)

A related article discussing Gustedt’s first defer implementation, which also looks at the generated assembly:

https://oshub.org/projects/retros-32/posts/defer-resource-cl...

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.

Implicitness of destructors isn't a problem, it's an advantage - it makes code shorter. Freeing resources in an explicit way creates too much boilerplate and is bug-prone.

> 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.

  • L-4
  • ·
  • 8 minutes ago
  • ·
  • [ - ]
> Implicitness of destructors isn't a problem

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.

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.
> A destructor can’t automatically handle the case where something doesn’t need to be cleaned up on an early return

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.

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 write C++ every day (i actually like it...) but absolutely no one is going to switch from C to C++ just for dtors.
  • kibwen
  • ·
  • 29 minutes ago
  • ·
  • [ - ]
No, RAII is one of the primary improvements of C++ over C, and one of the most ubiquitous features that is allowed in "light" subsets of C++.
  • Pay08
  • ·
  • 1 hour ago
  • ·
  • [ - ]
Weren't dtors the reason GCC made the switch?
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.

  • qsera
  • ·
  • 59 minutes ago
  • ·
  • [ - ]
>pretty reasonable

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.

I get your point, though in the specific case of defer, looks like we both agree it's really a good move. No more spaghetti of goto err_*; in complex initialization functions.
  • qsera
  • ·
  • 12 minutes ago
  • ·
  • [ - ]
>we both agree it's really a good move

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.

That comment is saying to use C++, not to add destructors to C.
  • Mond_
  • ·
  • 59 minutes ago
  • ·
  • [ - ]
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).
> 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.

  • majke
  • ·
  • 59 minutes ago
  • ·
  • [ - ]
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.

> still stay with C89

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.

Just straight up huffing paint are we.
Explain why? Have you used C99 designated init vs other languages?

E.g. neither Rust, Zig not 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...

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.

[1] https://www.gingerbill.org/article/2015/08/19/defer-in-cpp/