9 ms·
Despite being convenient,I have the feeling that it might be a bad idea. One of the key interest of C compared to more recent languages is that everything is e
by greatgib 6y ago
Despite being convenient,I have the feeling that it might be a bad idea.
One of the key interest of C compared to more recent languages is that everything is explicit. With a finger you can follow the code as it runs and know exactly what is going on and when exactly.
At the opposite, there is c++ that does a lot of things automagically. And it is often hard to understand why you suddenly get a segfault out of blue, just because a destructor was randomly called at the wrong time.
- coldtea 6y ago>One of the key interest of C compared to more recent languages is that everything is explicit. There's nothing implicit about defer.
- tangus 6y agoDeferred actions are not explicit at the exit points. That's quite implicit. You can no longer reason about a local piece of code; you now have to know its lexical nesting up to top level to see if it's inside a guard block that might trigger hidden behavior.
- coldtea 6y agoThat's still local at the scope level though, which is quite acceptable. Plus, to handle the free or the leak if you had forgotten to free a resource at the exit point would also require to "know its lexical nesting up to top level". Between goto and longjump and co, C has much worse non-local behavior than defer.
- josephcsible 6y agoGoto isn't nonlocal. You know you'll only every jump from them, and that you'll only ever jump to the specified label.
- coldtea 6y agoThe specified label is what makes goto no-local. You need to check the whole codebase to find out where you'll land. By your definition only [1] "come from" would be non-local. [1] https://en.wikipedia.org/wiki/COMEFROM https://en.wikipedia.org/wiki/COMEFROM
- josephcsible 6y ago> the whole codebase You can't goto out of a function, and you know there's exactly one such label inside it. If goto isn't local, then neither are function calls, since the function could be defined anywhere in the codebase.
- coldtea 6y ago>You can't goto out of a function You can with a goto expression and a label address available - though the behavior is undefined in C, so bets are off. And you can with longjump/setjump more explicitly.
- josephcsible 6y agoAre you talking about this? https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html It's a GNU extension, not part of standard C at all.
- gpderetta 6y agoFWIW, Normally the term "non local goto" is reserved for control transfer beyond the current activation frame. So C goto is strictly local, bit longjmp would be non-local.
- sramsay 6y agoI wondered about this. Say I have a block, at the end of which I free a bunch of memory. I also have a bunch of other exit points within the block (mostly for catastrophic errors, say). Would a deferred free only apply to the outer scope? Because if so, I really don't see the point at all.
- dnautics 6y agoyes, you always run defer. I don't see it in this proposal, but Most languages/frameworks that implement a defer also implement a "error defer" which only gets triggered on some sort of labeled early exit scenario, and some implement "success defer": (i believe this is scopeguard: https://www.youtube.com/watch?v=WjTrfoiB0MQ https://www.youtube.com/watch?v=WjTrfoiB0MQ)
- dnautics 6y agoit's control flow. What you are saying is like saying "while loops are implicit: you can no longer reason about code; you now must think about the state of the check boolean to see if it will trigger the hidden behaviour of going back to the top of the loop because there's no explicit "go back to the top of the block" statement.
- josephcsible 6y agoWith a while loop, to know what happens at the bottom of the block, you only need to check the top of the block. With defer, to know what happens at the bottom of the block, you need to check the entire contents of the block.
- IAmADHDToo 6y ago> With a while loop, to know what happens at the bottom of the block, you only need to check the top of the block. Anyway, what could possibly happen at the end of a while loop, besides going back to the begining for the test? Besides, if you have a bug in your code, you will have to look at the whole block anyway.
- chongli 6y agoWhat? Any statement inside a while loop could mutate the loop variable and then all bets are off. You have to check every line of a while loop to know what’s going on. Heck, another thread could hold a pointer aliasing the loop variable and then mutate it, causing the loop to terminate for no obvious reason.
- josephcsible 6y agoMy point is that you know at the end of the while loop, it's going to test the loop variable you wrote at the beginning, no matter what's in the loop body. The fact that other things could change the variable isn't relevant. With defer, you don't know what will happen at the end of a block without looking through the whole thing.
- SPBS 6y agoIt's as much hidden behaviour as destructors being called magically on an object that goes out of scope. In practice it doesn't hinder understandability as much as you think.
- josephcsible 6y ago> destructors being called magically on an object that goes out of scope Which C doesn't have.
- dragonwriter 6y ago> Deferred actions are not explicit at the exit points. They are no less explicit than the actions performed at the end of iterations of for or while loops. In general, for C, understanding the behavior of code requires understanding “is it in a block, and if so what kind of block”; guard blocks would be not generally different.
- apankrat 6y agoEvery defer statement is ultimately pushing a lambda into some stack that is executed when the defer block is exited. With an exception of setjmp/longjmp, I can't think of an existing C construct with similar run-time complexity.
- IAmADHDToo 6y agoThat's indeed tricky: if there's a for loop inside the guarded block which generates many defers, a stack would have to be created to handle them somehow.
- saagarjha 6y agoThe defer would just run at the end of each iteration.
- deleted 6y ago[deleted]
- skohan 6y agoIs it actually a lambda, or is it just essentially appending statements to the end of the scope?
- anfilt 6y agothat depends for instance you can safely call free on NULL so you could just append. However, for some things you can only free/return resources if you successfully created that resource. At which point you would need to use something like a stack.
- skohan 6y agoI think the broader and more accurate point is that defer adds cognitive load to reasoning about the order of execution. It's true that defer (at least everywhere I've seen it executed) is totally explicit and deterministic, but in the case of multiple defers in the same block it can take some thought to reason through exactly what happens when.
- zabzonk 6y agoDestructors are not called randomly.
- sillysaurusx 6y ago"Smart pointers go brr" It's not really random, but it's quite hard to follow.
- lultimouomo 6y agoThat's really an argument against smart (to be precise, shared) pointers, not against destructors.
- ben509 6y agoIf it's too cold for you, it's too cold for your smart pointers. Bring your smart pointers inside during the winter months.
- eropple 6y agoIt shouldn't be. std::unique_ptr is very clear. (std::shared_ptr should be used only when absolutely required and should be kept under close watch the whole time.)
- djmips 6y agosearches codebase I'm working on... finds thousands and thousands of std::shared_ptr (many involve a typedef, so there are even more...) eep! Should I be alarmed?
- hedora 6y agoYes. On reflection, or on ramping up new developers, I think you’ll find that it is unnecessarily difficult to reason about object lifetimes. There’s a good chance that most of the shared_ptr’s can be replaced by unique_ptr, which has less runtime overhead. More importantly, it documents the intent of the programmer regarding ownership semantics, and the timespan during which the object should be remain valid.
- yvdriess 6y agoguard/defer is semantically and syntactically as explicit (or implicit) as C's automatic storage class (https://en.cppreference.com/w/c/language/storage_duration https://en.cppreference.com/w/c/language/storage_duration), which is the default storage class.
- fanf2 6y agoOnly if you include dynamically sized arrays, which are deprecated because of their problematic allocation behaviour.
- shakna 6y agoI don't believe that VLAs are actually deprecated as such, but have been moved to an "optional" feature for implementation in C11. There's a feature macro to check, __STDC_NO_VLA__, but I don't think the feature is actually disappearing from the standard any time soon.
- cassepipe 6y agoI wonder what is a good use for VLAs btw. I used it for a string padding function to create the padding with a simple loop before a call to strjoin. Is that a bad idea or a legitimate use case?
- saagarjha 6y agoDon't use VLAs for anything that actually requires an allocation. However, VLAs are quite useful when you have a buffer and want to access it like an array.
- brudgers 6y agoDespite being convenient,I have the feeling that it might be a bad idea. What is "I am thinking of using C?"
- dkersten 6y agoDepending on your platform, it may be your only reasonable choice.
- brudgers 6y agoI agree completely. For the most part it seems if a person has to think long and hard about it, they probably should not use C and if it is the obvious choice that’s probably because C is ordinary in the context. These days there are probably fewer edge cases than in the past.
- whatshisface 6y ago>One of the key interest of C compared to more recent languages is that everything is explicit. With macros this is not exactly true. I gesture towards the GObject system for an extremely complex situation in big important production software.
- quelsolaar 6y agoI agree. I have tried to come up with some reasonable way to constrain macros, but its really hard!
- whatshisface 6y agoThe way to do it is, survey your macro use to identify common patterns, specify them formally, and then write a computer program that allows those patterns specifically but no others. In other words, design a higher-level language. ;)
- desiderantes 6y agoSomething like https://wiki.gnome.org/Projects/Vala https://wiki.gnome.org/Projects/Vala ?
- dnautics 6y ago> With a finger you can follow the code as it runs and know exactly what is going on and when exactly. Oh yeah? https://www.youtube.com/watch?v=Gv2I7qTux7g?t=29m21s https://www.youtube.com/watch?v=Gv2I7qTux7g?t=29m21s
- Someone 6y agoSo, what’s the alternative? Not freeing resources is a very common error; it would be nice if the compiler could help detecting it. A possible explicit solution I can think of is to introduce a new function attribute that gives the name of their ‘cleanup’ function (so that the compiler would know fopen needs a fclose, for example) and a compiler that uses these attributes to issue a warning if a function has a path that calls a function and doesn’t either call its cleanup function or returns its result. I don’t know whether that would cover all bases, though.
- Asooka 6y agoI view it as another element of structured programming. It can be expressed as a series of "goto" statements, same as for, while, do, switch. It's just one they didn't think of back when C was being designed. If it was in from the beginning, nobody would think it strange. That said, it's still debatable if it's useful, given that you can achieve the same thing with the struct some_resource resource; do { resource = allocate(...); if (!resource) break; } while(0); if (resource) dispose(resource); I can see it as a good thing because you have the dispose statement next to the allocate statement, which makes the logic easier to follow, but the implementation may have caveats which make it actually harder to reason about, e.g. see the other thread about capture value vs capture reference - C will most probably need to capture by reference, which means that modifying "resource" later on changes the meaning of the deferred statement.
- rseacord 6y agoI've heard this comment more than once. What we are trying to accomplish is to collocate the resource acquisition code with the acquisition release code. This does mean that the release code is removed when where the release occurs (for example, at every location a function returns. However, this is not without precedence in C. For example, just look at the for loop: for (clause1; expression2; expression3) statement expression3 is executed after statement.
- simias 6y agoI would argue that the C for loop is a rather awkward construct. It's found its way in many languages, so I think most people are used to its idiosyncrasy but it's not great if you try to take a fresh look at it. I think the best defense of this syntax is that it makes writing basic iteration a bit nicer without having to add boilerplate (the iconic `for (i = 0; i < n; i++)`) but then I would argue that the real problem is that C is severely lacking in the iteration department and this is a rather obvious hack (that languages like Javascript felt the need to copy wholesale, for some insane reason).
- scythe 6y agoThe nonlocality can be eliminated by replacing the `guard {}` block with a `resolve;` statement to be placed at the end of a block containing multiple `defer`s. This also reduces nesting and solves the question of where the `defer` is executed and makes it easy to grep to the location where the `defer` statement will be executed. Of course, it would be a syntax error to use `defer` without a following `resolve;`.
- pornel 6y ago"Explicit" in language design is catch-all term for several different things: https://boats.gitlab.io/blog/post/2017-12-27-things-explicit-is-not/ https://boats.gitlab.io/blog/post/2017-12-27-things-explicit... (I highly recommend this article.) Defer is still manual and local, just less noisy and burdensome. Just like every C feature: if you know how it's implemented (and optimized), you will know what is going to happen. All big C compilers already support stack frames and unwinding, so it's not even entirely novel functionality. While you may object it's not entirely obvious how unwinding is going to be implemented, OTOH in functions with complex control flow it can be easier to understand which `defer`s are going to be run, as opposed to following nested `else` statements, or reasoning about the program state from all `goto cleanup` locations.
- sudobash1 6y ago> One of the key interest of C compared to more recent languages is that everything is explicit. With a finger you can follow the code as it runs and know exactly what is going on and when exactly. I would suggest functions like atexit and pthread_cleanup_push as well established counterexamples. Granted this is not a perfect comparison because these are implementable without extending the c language; however, I think they have the same general idea of "defering" cleanup. I think the proposed defer functionality is actually more readable because the defer command will be written much closer to where it will be exited. Compare this to atexit() which may be put anywhere.
- btilly 6y agoOne of the key interest of C compared to more recent languages is that everything is explicit. With a finger you can follow the code as it runs and know exactly what is going on and when exactly. This has not been true in many years. C appears to be such a language, but optimizing compilers have learned how to find and optimize undefined behavior in code that most C programmers don't realize is unsafe. As a result there can be a considerable gap between the code as clearly intended, and the code that will be generated. See https://blog.regehr.org/archives/213 https://blog.regehr.org/archives/213 for more on this. Including real world examples of things like validation checks being elided by the compiler, leading to real-world vulnerabilities in programs which clearly have checks to avoid exactly those vulnerabilities.
- Animats 6y agoDespite being convenient, I have the feeling that it might be a bad idea. Probably. It's one of Go's lesser ideas. C already has a "defer" mechanism in "exit", to close out files and such. Of course, the final I/O status gets lost.
- Technically 6y ago> One of the key interest of C compared to more recent languages is that everything is explicit. With a finger you can follow the code as it runs and know exactly what is going on and when exactly. I don't agree! There's a lot of behavior that's implicit and you essentially need to internalize the C standard/compiler behavior to follow. Weak typing, for instance; defaults for memory access/fencing, handling faults, runtime semantics with respect to initialization of the process, cleanup via atexit, and signal handling. Memorable, sure, but hardly explicit.