17 ms·
C2x: the next real revision of the C standard
- Aardwolf 8y agoThey should add something to run code when leaving a scope, no matter how you leave the scope (break, return, ...). That would allow cleanup and other such actions without resorting to such hacks as: "goto cleanup" pattern, separate functions, fake for loop to break out of, ...
- majewsky 8y agoThe idiomatic way to do that is with destructors. EDIT: Sorry for the confusion, I misread the article and thought this was about C++2x.
- mouldysammich 8y agoC doesn't have destructors, does it?
- vkazanov 8y agoYeah... Actually adding something like defer {...clean up code...} would be really nice. But who are we to ask..? Just programmers, i.e. mere mortals nobody really cares about. :-)
- stinos 8y agoYou can use C++ as some kind of C with destructors though :P Scoped cleanup is really a nice thing.. But then you also want templates of course to get rid of your void*. And oh, wait, what's that? A cross-platform thread implementation (well, sort of, depends on platform)? A string thing which I can search without strstr? Anonymous functions which capture? Auto? Gimme gimme :]
- beefhash 8y ago> You can use C++ as some kind of C with destructors though :P Scoped cleanup is really a nice thing.. C++ is not a strict superset of C. You actually have to cast void pointers, for example. > But then you also want templates of course to get rid of your void*. No, actually, I think I can live without that, but thank you. > And oh, wait, what's that? A cross-platform thread implementation (well, sort of, depends on platform)? C11, threads.h. Been there, got that. > A string thing which I can search without strstr? Okay, I'll give you that, string handling is hell. > Anonymous functions which capture? Have their uses, but I'm not sure if C is really the right place for it. > Auto? auto (as used in C++11 and later) is a solution in need of a problem in C. When you don't have piles of templates and iterators, you also tend not to need to automatically derive types. In a world where signed/unsigned integer comparison can have fatal consequences, you probably do want to be very sure about your types.
- rubber_duck 8y ago>C++ is not a strict subset of C. I think you flipped this :) ?
- stinos 8y ago> C++ is not a strict superset of C. I know that. I use both C and C++ practically daily. The post was partly joking. But only partly (for example of course I could live without templates if really needed but seriously they make some jobs a lot better and easier). Hence I aptly phrased it some kind of C hoping (idly it seems) no one would trip over it because it's obviously not C.
- Dylan16807 8y ago
- shaklee3 8y agoNot the language, but some compilers have something similar: https://stackoverflow.com/questions/2053029/how-exactly-does-attribute-constructor-work https://stackoverflow.com/questions/2053029/how-exactly-does...
- Aardwolf 8y agoYep, talking about C here, not C++. If they would add that feature, you could use macros to get constructor and destructor like behavior (as long as it's within the same scope, you could write a macro that constructs your object, and in addition contains something like "at scope exit: run this function"), which would be super useful and as far as I'm aware not very complex for the compiler (as all they have to do is run some code whenever exiting scope) nor very far outside of the spirit of C (it's still very low level, just a small convenience feature with interesting implications, especially when used with macros).
- kazinator 8y agoC++ is a dialect of C. It is the result of starting with C, and then accommodating a massive, sustained sequence of feature requests, exactly like ones we are seeing in this thread. Everyone thinks that if just their pet feature request is added to C and everyone else's ideas are rejected, it will still be C.
- bunderbunder 8y agoC++ is more than that; it's a set of additional features that create something of a C-flavored multiparadigm language. Which inevitably does turn it into a kitchen sink language, since it's trying to be all things to all people. This idea doesn't seem to be in that spirit to me. It's not trying to do something radical like, say, adding OOP semantics to C. It's suggesting that C, a structured programming language, get a feature designed to improve the ergonomics for people doing structured programming in C.
- MaxBarraclough 8y agoBrief aside: Boost has a facility for doing this in C++ without declaring a new class. (It boils down to a destructor, but it's more compact.) https://www.boost.org/doc/libs/release/libs/scope_exit/doc/html/index.html https://www.boost.org/doc/libs/release/libs/scope_exit/doc/h...
- aaaaaaaaaab 8y agoBoost.ScopeExit does declare a new class via macros.
- MaxBarraclough 8y agoYes, and I hinted at this, but it's more compact.
- nwallin 8y agoDo they have a new version based on lambdas? The syntax of that is painful. I splatter my code with this: // WTFPL class Finally { std::function<void()> f; public: Finally(std::function<void()> f) : f{f} {} ~Finally() {f();} void disable() { f = [](){}; } }; Which looks much prettier: socket* s = open_socket(); // or whatever Finally cleanup_socket{[](){ close_socket(s);}}; // optionally, to keep it alive: cleanup_socket.disable(); Am typing on mobile. No guarantees about syntax errors. I still need to look into where the right places to put r value references and/or std::move are, but for the most part, I never put anything other than a pointer in the closure so I'm not worried about copy constructor cost.
- Matthias247 8y agoHowever your implementation based on std::function might allocate, which is then non-zero cost compared to normal exit statements. Better directly store the lambda inside the class, which requires that to be generic (Finally<LambdaType>). That can be hidden by using the class via a templated function which uses types interference: auto cleanup_socket = make_scope_guard([&]{ close_socket(s); }); Searching for scope_guard yields lots of alternative implementations.
- megous 8y agoYou can do it with GNU C. It would be nice if it was standard.
- kazinator 8y agoYou can do it in Bjarne Stroustrup C, which is standard. You can do it in the 20-year-old version of it, and draft versions many years before that.
- sifoobar 8y agoC++ has about as much to do with C as Java with JavaScript these days though. It's just not an option in many cases where C is fine. I've gone back and forth the last 20 years or so, and have plenty of experience with both languages. Even the experts are beginning to loose faith, it's just getting too damn complex. I'll take variants as an example, the hoops people are willing to jump through to get something as basic as unions working properly is just insane. It looks more like religion than programming from here, Rust has the same cult like behaviors going on all over the place. Edit: Ah, I see; you're more worried about them turning C into the next C++ :) I might even agree some days.
- gpderetta 8y agoPlease, C and C++ share a large subset, and, most importantly a memory model. Java and JS share, what, a couple of parentheses?
- stochastic_monk 8y agoMost C is inducted into C++ eventually. The point is that it would be nice to have something like RAII without subscribing to the full C++ perspective.
- jcelerier 8y agowell, compile with a C++ compiler and just use RAII ?
- gkfasdfasdf 8y agoYou can do this with GCC/CLang via the cleanup attribute: https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attribute... It would be nice to have this be a part of the standard.
- jws 8y agoIt's very useful. I use it for scoping the holding of locks. It replaces the idiom where you make a separate function to hold the 'when locked' code and pass all required state back and forth with nice clean inline blocks of code.
- plop_ 8y agoSomeone should submit a proposal.
- CyberDildonics 8y agoI completely agree, I think this is something that C desperately needs. D has scope(exit){...} which is similar to constructs like defer {...} Many things can be done in some form with macros and the C11 generic keyword if they have to be, but defering statements to run on scope exit is still elusive as something that can be relied upon. https://tour.dlang.org/tour/en/gems/scope-guards https://tour.dlang.org/tour/en/gems/scope-guards
- kazinator 8y agoC desperately needs to be left alone.
- dymk 8y agoYou've made a few comments like this; care to explain your thoughts rather than just say a bunch of variations on "nooooo!"?
- kazinator 8y agoThe C language is finished and great as it is. Many programmers like myself have no problem with it whatsoever. Change in a key infrastructural component like this is only destabilizing. The ISO C people should have the decency to disband and work on their pet language research projects in private.
- jononor 8y agoYou are free to stay on C89 or C99. They are not going away anytime soon, too much code relies on it.
- kazinator 8y agoIf you think if standard-driven changes to the compiler will never break your C89 code, because you're using the -std=c89 switch or whatever, you are pretty naive. The only guaranteed way your compiler won't break your code is if it's left alone.
- v_lisivka 8y ago/** * GCC and Clang extension to call cleanup function at exit * from the function with pointer to given function as argument. */ #define defer(func) __attribute__((cleanup(func))) #ifdef _CRUST_TESTS // Sample destructor, to test defer static void _tst_charp_destroy(char * * value) { if(*value) { free(*value); *value = NULL; } } // Test case it(defer, "must deallocate object at the end of the function") { defer(_tst_charp_destroy) char * s = calloc(1, sizeof(char)); (void)s; } #endif
- kazinator 8y ago> They should add something I disagree. > to run code when leaving a scope, no matter how you leave This, and various other features, were already added to C long ago. The resulting dialect was called C++.
- bunderbunder 8y agoI'm not sure I understand what you're getting at here. Are you implying that people who want new features in C should just migrate to C++ because it has even more features? Or that C is perfect as-is and anyone who wants to add new features to it should bug off to another language? Or that this particular feature is somehow equivalent to (or a slippery slope toward) adding a whole set of OOP features to C, so we might as well take that to its logical conclusion?
- kazinator 8y agoPretty much all of the above.
- bunderbunder 8y agoI'd like to hear you elaborate. You seem to be very invested in your concerns, but it's hard to understand exactly what they are. A single, clearly articulated response would do a lot more than a fusillade of terse barbs to help others understand why you think this is a bad idea.
- MrRadar 8y agoThey probably don't want to because then they'd have to specify how they would interact with the setjmp/longjmp functions (which are, in fact, specified as part of the ISO C standard, section 7.13 in C11).
- grive 8y agoThe hacks you have listed have the advantage to be visible. Reading the code, you know whether they are called or not. The issue with cleanup on scope exit is that this introduces ambiguous code-flows. You would need to demonstrate a strong advantage, beyond making life easier for the writer of the code.
- isaachier 8y agoOnce you do that, you more or less recreate C++. IMO C vs. C++ is fundamentally an issue of RAII and arguably templates. This proposal would add RAII to C.
- anticensor 8y agoYou have seem to have left C++ in 1999. C++ has expanded so much that someone can create its own operating system just by adding drivers around its standard library.
- vkazanov 8y agoI will just pray for the better error handling proposals. Both are fine. For modern code with no global state, especially the multithreaded kind, everything is better than the errno.h mess.
- jstimpfle 8y agoI don't think "error handling" should be a thing in C. Errors are just data, not a special case. errno.h isn't so much builtin to C. It's just part of the standard libary, and more so of POSIX. It's only used for interfacing with the OS. And it's not that bad, since errno is a thread local variable.
- vkazanov 8y agoC is not a holy cow, is it? It's just a very, very popular language. Error handling is important in programming in general, and having ways to implement it conveniently helps a lot. Yes, errors are just data. And everything is data, including the code itself, right? It a question of abstractions introduced to the language and the program at question. errno.h is bad. It's inconvenient, it's global, even if it's a thread-local something, it's cumbersome to use. AFAIK, there are 2 error-related proposals for inclusion. One is making errors special, the other is a bit more generic. Both would improve on the current situation.
- jstimpfle 8y agoYou don't need to change the language. You need to add new functions to the standard library. There are already quite a few versions of older functions, with an "_r" suffix in their names (from the top of my head, strtok_r(), although that is not a great example) that take an explicit pointer to local state, eliminating global state. You could just make more of them if you want to eliminate errno. > It a question of abstractions introduced to the language and the program at question. I don't think these kind of abstractions are in the spirit of C. As it says in the Charter linked here, "provide only one way to do an operation". A more acceptable way to me would be allowing multiple return values in general. But maybe there are technical reasons why this is not done. Or it has to do with the complexities that such a mechanism would add to the expression syntax.
- kragniz 8y ago>Add a type aware print utility with format specification syntax similar to python Does anyone have more information about this proposal?
- beefhash 8y agoWishlist: the arc4random family (would also put up with it being in POSIX), strlcat and strlcpy (yes, glibc, just for you), getline (fgets sucks), reallocarray and recallocarray, that signed integer overflow becomes at least implementation-defined rather than pure undefined behavior, ideally fix the notion of locales and guarantee (u)int8_t == unsigned char if (u)int8_t exists (lots of code actually relies on that).
- Sir_Cmpwn 8y agogetline is POSIX. If you want to see arc4random in POSIX, you should write to the Austin Group mailing list: austin-group-l@opengroup.org. They also have public biweekly meetings you can attend and present your case at.
- beefhash 8y agogetline is POSIX, but not C. I feel like the functionality is so fundamental to writing C as securely as the language allows that it ought to be promoted to being in the C standard. arc4random is in complete POSIX limbo as far as I can tell. First started as a rename to posix_random[1] and then OpenBSD slammed the door shut by withdrawing it and now we're at risk of getting the worst of both worlds with Linux's getrandom[2]. [1] http://austingroupbugs.net/view.php?id=859 http://austingroupbugs.net/view.php?id=859 [2] http://austingroupbugs.net/view.php?id=1134 http://austingroupbugs.net/view.php?id=1134
- pjmlp 8y ago> Improve array bound propagation and checks Looking forward to this one, specially since Annex K ( Bounds Checking Interfaces) has proven to have not solved anything and is now scheduled for possible removal. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1969.htm#adi http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1969.htm#ad... These other ones are also interesting from security point of view. > Add a new calling conventions with error return for library functions that avoids the use of errno > Extend specifications for enum types > Add a simple specification of nullptr, similar to C++
- rurban 8y ago> Looking forward to this one, specially since Annex K ( Bounds Checking Interfaces) has proven to have not solved anything and is now scheduled for possible removal. It has solved the usual bounds errors on those who use it. I.e MS, Embarcadero and safeclib. Since glibc, musl and freebsd libc refuse to use the Annex K it's easy to blame just them, not the safe extension, which do serve their goal. With safeclib you even get compile-time checks, more than with the simple _FORTIFY_SOURCE=2 checks. Only Android Bionic got a bit better lately. safeclib is as fast or even faster than the fragile assembler bits in glibc. > Add a new calling conventions with error return for library functions that avoids the use of errno That's of course part of Annex K. What's urgently missing is still a proper string API. ASCII str* goes nowhere, wide char wcs* is not widely used, 80% use utf8. wcslwr, wcsfc, wcsnorm are even missing. The whole u8* string API is missing, and not even discussed. ICU, libutf8 and libunistring don't get you far. coreutils still cannot handle non-ASCII strings.
- pjmlp 8y agoNot at all, because it doesn't fix out of bounds errors caused by copy-paste errors where the given buffer size doesn't match the actual size of the declared buffer or string. A situation which is described on the field report I linked to. Only C++ compilers like Visual C++ which provide overloaded versions of Annex K without size parameter thanks to the improved C++ type system, do actually provide a real usable version of Annex K. But then it isn't C anylonger.
- 0x09 8y agoThe linked discussion on the memory model is particularly interesting to me as it covers a number of issues and ambiguities with the current specification for strict aliasing and what kind of accesses should/shouldn't be allowed, including for example the problem that there's no way to obtain untyped space on the stack (Q75). Since this as a whole is among the least consistently implemented and (arguably based on the number of questions it generates) least well understood aspects of the standard it's nice to see some authoritative efforts to clarify the intended behaviors. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2294.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2294.htm
- saagarjha 8y ago> the problem that there's no way to obtain untyped space on the stack (Q75) As in a standard alloca?
- gpderetta 8y agoFun fact: alloca is neither in (any) C standard or POSIX. It is just a very old extension, implemented in many compilers with somewhat compatible, under specified semantics.
- pjmlp 8y agoVery old indeed, Turbo C 2.0 for MS-DOS already had it. Not sure about the Small C dialect from early 80's.
- saagarjha 8y agoI am aware of that, which is why I said “a standard alloca” instead of “the standard alloca”. I’m asking if they’re proposing adding a version of alloca to the standard.
- aidenn0 8y agoWhile you can't get untyped space on the stack, it is explicitly permitted for objects of character type to alias objects of other types. I don't see how effective_type_3.c has undefined behavior.
- nrclark 8y agoRequest for C++14-style constexprs. It would be a great way to spice things up, and I think would be very compatible with the C philosophy. C is a great language, and I love working with it. But constexpr is something I really feel would improve the language (by eliminating the need for complicated #define macros). C++14's constexpr was a breath of fresh air when I first used it. It basically lets me write real code which evaluates at compile-time and can generate constants. I'd love to see constexpr ported over to C.
- rwbt 8y agoI think having a primitive templating system would also reduce the usage of macros. While we're at it throw in AST macros too.
- AnimalMuppet 8y agoYour second request seems considerably outside the style and philosophy of C. Or was that sarcasm?
- rwbt 8y agoYep, it was made jokingly trying to make a point about the slippery slope of 'bloat'. But didn't go that well.
- AnimalMuppet 8y agoIt went all right, once I adjusted my sarcasm detector...
- nrclark 8y agoOut of curiosity, would you consider constexpr to be bloat? I feel like it has tons of applications, especially for embedded C programmers. One example that comes to mind: CRC calculation. Most microcontroller CRC libraries are lookup-based, or a mixture of a lookup table and other methods. Currently, a lookup table can be done only 3 ways in C: pre-compute it and store 'magic numbers' (either while developing, or with some custom pre-processing), compute at program initialization (which costs code-space and startup time), or a compile-time computation based on some very ugly macros. With constexpr support, I could just write a C function that calculates the table values. Then I could use it to populate a constexpr table at compile time, or even use the function at runtime if I needed to do some debugging. C already has sizeof, which is a compile-time computation. Why not let users write their own compile-time functions too? I recently wrote a command-lookup library in C++14. Using constexpr, I could precompute the hashes of each string and populate a switch() statement. Plus I could use the exact same function to hash my incoming strings, even if they're of unknown length. That's not possible in C at all, not even with loop-based macro trickery.
- GautamGoel 8y agoWhat about concurrency?
- muricula 8y agoThere was a lot of work done on that in the C11 release with updates to the memory model and thread.h. I have heard some criticisms of thread.h APIs which could be addressed, such as the ability to specify stack size. There are C++2x proposals to add a green thread/goroutine style mechanism. I'm not convinced that it's something which belongs in the C core language or C standard library though.
- bumblebritches5 8y agothreads.h* Just for any casual readers unaware
- man-and-laptop 8y agoWill anything be done about this problem? https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f027338b0fab0f5078971fbe https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f02...
- pilif 8y agoThis reads like a problem with the POSIX libraries and not with the C language itself, so it‘s probably not up to the language to fix it. C actually comes pre-equipped in a pretty nice position with its default 8 bit char data type (which is perfect for UTF-8). The POSIX standard however, I agree is in serious need of an overhaul for locale features and you‘re probably better off ignoring it completely and just going ICU these days anyways - though then you have to go the extra length to still use the OS provided means (LC_* env under Unix) to get to the user‘s preferred locale. But once you have that, yeah, ICU is probably the way to go for actual string formatting.
- detaro 8y agoLocales and the most basic functions around them are defined in the C ISO standards. (e.g. section 7.11 of http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)
- boznz 8y ago#DONOTOPTIMIZE (sigh..)
- The_rationalist 8y ago' char8_t: A type for UTF-8 characters and strings, see N2231 ' What does this mean ? C11 already brought the u8 type
- rurban 8y agochar8_t is the type, u8 is just a prefix for constants, like u8"xxx"; And it's only in C11++, not C11 AFAIK.
- The_rationalist 8y agoYou are right, this is only for string litterals (so read only).But Wikipedia C11 mention the feature, what do you mean by c11++ ? Btw c17 added 0 feature.
- bumblebritches5 8y agou8 exists for string constants, but not character constants. they're proposing to add u8 as a character constant prefix.
- baybal2 8y agoC is older than me, but it still has so much things to improve. And I am very glad that it is still being actively improved.
- capsicum80 8y agoPrevious attempts to doing this have introduced unnecessary ugliness to the language such as the possibility to mix declarations with code. I can only see the language getting worse by introducing new pointless features. Unnecessary bloated C already exists and it is called C++
- Twisol 8y agoBy "mix declarations with code", do you mean the ability to put local variables like `int x;` in locations other than immediately at the start of a function? I don't understand why this is a bad thing.
- capsicum80 8y agoThis, and especially in the first argument of 'for'. Not back compatible, very inelegant and luckily discouraged in many projects' coding guidelines.
- capsicum80 8y agoActually it is block, not function. It makes it very difficult to read the code if you are looking for the scope of the variables, or investigating stack usage.
- Mikhail_Edoshin 8y ago(In C you can have local variables inside any block, e.g. 'if' or 'for'.) It's subjective, of course, but I find it much clearer to have a dedicated place to look for variables.
- rwbt 8y agoI hope they make real progress on improving the C language, not just slap on yet another library/header to the standard lib (cough.. <complex.h> ..cough).
- vortico 8y agoC is a good language, but why does the standard library need to be in the language standard? It's perfectly possible for there to be competing modern libraries which implement everything from the stdlib which can be built completely from pure C source. Suppose I build libvortico, which had proper string handling, threading, filesystem, etc. There would then be no need to deal with stdlib quirks. Just use that as an alternative.
- umanwizard 8y agoYou're perfectly welcome to build your own library and put whatever you want in it. The reason there is a "standard library" is to make portability possible.
- vortico 8y agoBut portability has nothing to do with whether the library is standardized. One could port any API, whether from the standard or a simpleton like me, and port it in pure C and OS calls to any environment. One could even port a better API to wrap the stdlib calls, to add support for at least what the standard offers.
- umanwizard 8y agoYour argument goes through just as well for the base language itself. What's the point of having a C standard at all? Since you could just port your compiler to any platform...
- vortico 8y agoThe point of a language standard is to have multiple compilers and to be able to write code to some standard. The difference between these points is that with a "stdlib" alternative library, you can still have multiple compilers and write library function calls without following the standard, but simply the library's API. The reason I believe the stdlib shouldn't be a standard is for the same reason that libpng, libjpg, libzip, etc. aren't part of the C standard. It should be the software vendor's choice of which standard library to use.
- kevin_thibedeau 8y agoNext revision: Please stop kowtowing to recalcitrant compiler vendors too lazy to invest in updating their code.