8 ms·
C23 Implications for C Libraries
- synergy20 4y agowish defer made it, so I can kind of do RAII. even better, adding constructor and destructor for RAII in c, main() has it via attributes __constructor__ __destructor__, gcc has __cleanup__ for non-main() functions too, let's add it to C directly?
- KingLancelot 4y ago
- masklinn 4y ago> even better, adding constructor and destructor for RAII Constructors are a nuisance, and destructors while great require significant additional semantics to avoid double destruction. C++ uses unconditional destructor thanks to ubiquitous copying and non-destructive moves, but that requires all objects to always be in a destructible state. Rust instead relies on lexical drop flags inserted by the compiler if objects are conditionally moved. They’re more convenient and composable than defer/cleanup/scope, but they also have more langage impact. Obviously the trade off is defer pushes that issue onto the developer.
- mjburgess 4y agoI suspect `defer` is the mainstream right tradeoff between the implicit nightmarish semantics of C++ and the formalism of rust. I think the Rust view of C++ will turn out to be an over-reaction. The issue wasn't a failure to make the implicit explicitly provable, it was simply to make it explicit at all.
- masklinn 4y ago> I suspect `defer` is the mainstream right tradeoff It’s not. It’s a conveniently simple language addition which foists all the issues and edge cases onto the language user. Defer is a limited subset which is more verbose and more error-prone. However like “context managers” (e.g. try blocks, using, with, unwind-protect, bracket) it also works acceptably in languages where ownership concepts are non-existent or non-encoded, whereas destructors / drops require strict object lifetimes. > The issue wasn't a failure to make the implicit explicitly provable, it was simply to make it explicit at all. What, pray tell, would be the use of making borrows “explicit” then ignoring them entirely? Useless busy work?
- mjburgess 4y agoWell i didn't mean only defer, context managers also count as a 'making explicit'. My point is that requiring compile time proofs is likely too far to reach the practical goal. Indeed, it seems most Rust code today agrees: widely turning off the borrow checking with copies and the like.
- jamincan 4y ago> Indeed, it seems most Rust code today agrees: widely turning off the borrow checking with copies and the like. I here this and that `unsafe` is widely used in Rust code bases repeated a lot, but is there any actual data backing this?
- mjburgess 4y agoThere are three "dialects" of rust: borrow-checked, unsafe, and copy-everything. The existence of these three "dialects" goes to my point that the borrow checker isnt The Ideal solution to the problem of high-perf. safe static computing.
- anonymoushn 4y agoSome of this data may be difficult to collect, because some project leads evaluate Rust, discover that the entire ecosystem is built on top of libraries that endlessly thrash a global allocator with synchronization primitives in it, and move on.
- Fredej 4y agoOh man, no defer? Bummer. I'm switching from C++ to C recently and there sure are a bunch of things I'm missing!
- AlbertoGP 4y agoI made a small pre-processor that implements block-scoped defer in C, by transforming the source to add the deferred code at each exit point in a function. It is called Cedro: https://sentido-labs.com/en/library/cedro/202106171400/#deferred-resource-release https://sentido-labs.com/en/library/cedro/202106171400/#defe... That link goes directly to the relevant section in the manual. It includes a cc wrapper called `cedrocc` so you don’t need intermediate files, and it works hard to produce clean code for the generated parts. The rest is not modified at all. The goal is to be useful even if you only use it once to generate that repetitive code. The pre-processor `cedro` depends only on the C standard library, and `cedrocc` depends on POSIX.
- unwind 4y agoUh, not to be That Guy, but what did you expect? Just compare K&R [1] and Stroustrup (any edition) [2] next to each other, and you will get a pretty strong hint of C being a smaller language. That's kind of the point, or it used to feel like it was anyhow. [1]: https://en.wikipedia.org/wiki/The_C_Programming_Language https://en.wikipedia.org/wiki/The_C_Programming_Language [2]: https://www.stroustrup.com/4th.html https://www.stroustrup.com/4th.html
- pjmlp 4y agoFirst of all, if you are comparing K&R against Stroustrup, then you should use C++ARM, not later editions. Secondly, Bjarne's books include the overview of the standard library, which neither K&R nor its ANSI C revision do. Third, since everyone keeps using compiler extensions in C, moreso than in C++, those should be included as well.
- unwind 4y agoAt least in my ancient copy (second edition, from 1988 I think) K&R most definitely has an overview of the standard library, in Appendix B.
- quelsolaar 4y agoI'm in the wg14, and I made a passionate argument against defer. C is all about simplicity and clarity, over conviniance. Defer, is an invisible jump, its much better using a goto, that clearly denotes a change in flow. In C everything should be as clear and as explicit as possible. Nothing should happen without the user explicitly saying so. This means more typing, and thats fine, there are plenty of languages that offer loads of syntax sugar if thats what users want, but only C offers clarity.
- klodolph 4y agoI think this is the right approach. You can make C better without trying to compete with newer languages.
- pjmlp 4y agoYeah, why bother competing with newer languages on safety, that was never something that mattered on C's design.
- enriquto 4y agoThank you so much for your work! Your comment made me happy and warm inside, as if there's still some order in this crazy world. As if there's still a few sane and robust things that we can attach ourselves to, knowing that they will not break. How can we support/encourage you? (in case you need it)
- quelsolaar 4y agoSpeaking up is a good start! The support is much apprechiated!
- secondcoming 4y agoIf C is simple and clear why is it fraught with pitfalls? While C code can be nice and clear to read that doesn’t mean there less mental burden on the developer to keep track of everything going on.
- flohofwoe 4y agoA sane defer-like mechanism would be fine with me, but please no destructors (or worse) constructors, they are much too inflexible because they bind 'behaviour' to types. Data should be 'stupid' and not come with its own hardwired behaviour, otherwise this becomes a design-rabbit-hole that eventually ends up in C++.
- masklinn 4y agoWhile I agree that destructors are unsuitable for C, that’s because for them to be useful you’d have to throw out and redo the entire standard library, so they can’t be usefully retrofit in the language, however > they are much too inflexible because they bind 'behaviour' to types 1. that is the baseline you want, data is not an amorphous and meaningless blob, the default for a file or connection is that you close it, the default for allocated memory is to release it, etc… 2. that also allows much more easily composing such types and semantics, without having to do so by hand 3. and is much more resilient to future evolution, if an item goes from not having a destructor to having one… you probably don’t care, but if it goes from not having a cleanup function (or having a no-op one which you could get away with forgetting to call) to having a non-trivial cleanup function you now have a bug lurking 4. destructors also make conditional cleanups… just work, the repetitive and fiddly mess is handled by the computer, which is kind of the point of computers, rather than having to remember every time that you need to clean the resource on the error path but not on the non-error path, defers easily trigger double-free situations; this also, again, make code more resilient to future evolutions (and associated mistakes) 5. furthermore destructors trivially allow emulating defers, just create a type which does nothing and calls a hook on drop > Data should be 'stupid' and not come with its own hardwired behaviour That’s certainly a great take if you want the job security of having to fix security issues forever.
- flohofwoe 4y ago> ...the default for a file or connection is that you close it... Something like a file or connection is already not just 'plain old data' though. In my mind, 'data' are the pixels in a texture (while the texture itself is an 'object'), or the vertices and indices in a 3D mesh (while the 'mesh' is an object), or the data that's read from or written to files (but not the 'file object' itself). C is all about data manipulation (the 'pixels', 'vertices' and 'indices'), less about managing 'objects'. For objects, constructors and destructors may be useful, but there are plenty cases in C++ where they are not (textures and meshes in a 3D API are actually a good example for where destructors are quite useless, because when the 'owner' of the CPU side texture object is done with the object doesn't mean that the GPU is done with the data that's 'owned' by the CPU side object - traditional destructors can be used of course by delaying the destruction on the CPU side texture object until the GPU is done with the data, but why keep the texture object around when only the pixel data is needed by the GPU, not the actual texture object? A 'defer mechanism' is just the right sweet spot for a C like language IMHO.
- rwmj 4y agoDefer was a truly terrible suggestion (as presented). However the C committee should have standardized the widely used __attribute__((cleanup)).
- layer8 4y ago> The minimum value for N is 1 for unsigned types and 2 for signed. I wonder why they’re disallowing _BitInt(1). It would be a signed integer type with the possible values -1 and 0.
- crest 4y agoIf you assume twos complement (does anyone still insist one supporting ones complement ints for the sake of old DSPs and minicomputers?)
- mastax 4y agoTwo's complement is required in C23.
- cryptonector 4y agoProbably for the same reasons that 1-bit signed int bitfields are UB. I suppose they could have allowed it as you say, but... is there a need?
- layer8 4y agoIt creates a special case when you're converting between signed and unsigned _BitInt(N) and you want to abstract over the concrete N.
- hvdijk 4y agoAre they UB? What rule says they are? I would not be surprised by such a rule, but I am not aware of one.
- cryptonector 4y agoOh, it might be implementation-defined rather than undefined behavior. Sorry, I'm not going to look through the spec right now for this.
- ynik 4y agoA single-bit bitfield has only a sign bit, no value bits. Prior to C23 there was no guarantee of two's complement, so it was possible that such a field could only hold the value 0.
- malkia 4y agoShouldn't this: char16_t s16[2 * sizeof mbs]; be char16_t s16[sizeof mbs]; ?
- malkia 4y agoOh, I see now....
- cpeterso 4y ago> The maximum [_BitInt] value is provided by a new macro BITITNT_MAX Why “BITITNT” instead of “BITINT”? I hope this is a typo, but “BITITNT” is repeated in the example code.
- deleted 4y ago[deleted]
- layer8 4y agoThe typo isn’t repeated in section 14.2, however it’s still wrong, as the correct name is BITINT_MAXWIDTH.
- kasajian 4y agoThe next version of C should redefine C as a strict subset of C++. That is, at any given moment, a particular revision of C should be a subset of a particular revision of C++. Each new version of C++ would then cause a revision of C to be released.
- asveikau 4y agoThat would break pretty much every call to malloc, since C allows implicit cast from void* and C++ does not.
- layer8 4y agoThis wouldn’t be possible in an even remotely compatible fashion, due to C++’s name mangling, among many other reasons.
- optymizer 4y agoAs someone who writes C code and couldn't give a rat's ass about C++, I have to ask: why?
- cryptonector 4y agoCan't be done: it would break backwards compatibility. E.g., `struct foo` and `foo` are the same type in C++ automatically (as if `typedef struct foo foo`), but not in C.
- tsimionescu 4y agoIf anything, C++ could have decided to become a strict superset of C - they wouldn't even have to change too much and could do it without giving up backwards compat. C would have to change significantly to become a proper subset of C++, and pretty much no C program would still compile (because of int* c = malloc(sizeof int);).
- msla 4y agoEven if you're OK with breaking every call to malloc(), as the other poster said, plenty of C code has variables named things that clash with C++ reserved words, such as new, and, while it's possible for programming languages to simply not have reserved words, I think C++ implementation developers and programmers would rather avoid the kinds of things clever C++ programmers would come up with were those guide rails to be taken off. https://softwareengineering.stackexchange.com/questions/189699/what-non-theoretical-practical-programming-language-has-no-reserved-keywords https://softwareengineering.stackexchange.com/questions/1896... No reserved words in PL/I: https://www.ibm.com/docs/en/epfz/5.3?topic=sbcs-identifiers https://www.ibm.com/docs/en/epfz/5.3?topic=sbcs-identifiers > Identifiers can be PL/I keywords or programmer-defined names. Because PL/I can determine from the context if an identifier is a keyword, you can use any identifier as a programmer-defined name. There are no reserved words in PL/I. However, using some keywords, for example, IF or THEN, as variable names might make a program needlessly hard to understand.
- CyberRabbi 4y agoEdit: This comment was not accurate
- layer8 4y agoUnix/Posix time doesn’t include leap seconds (it’s 86400 seconds per day, always, per definition [0]), whereas UTC, taken as a count of actual seconds, does include leap seconds. So you are right that converting between them requires additional data. However, few applications care about converting between Unix time and that notion of UTC, but instead care about converting between Unix time and calendar dates and times of day and time zones, which is easier with Unix time than with a UTC seconds count. So I think you’re mixing things up here. [0] https://en.wikipedia.org/wiki/Unix_time#Definition https://en.wikipedia.org/wiki/Unix_time#Definition
- CyberRabbi 4y agoIn the link you provide it says this about Unix time: In Unix time, every day contains exactly 86400 seconds but leap seconds are accounted for. It then provides an example for when the Unix time went from 915148800 to 915148800 after 1 atomic second on 1998-12-31T23:59:60.00 So it's incorrect to say that Unix time does not include leap seconds.
- butlerm 4y agoIt would be more accurate to say that Unix time "accounts for" leap seconds by not accounting for them at all, but rather switching into temporal displacement ambiguous repeat timestamp la la land for an entire second before returning to an unambiguous encoding of UTC.
- layer8 4y agoLeap seconds are not counted in Unix time. Otherwise days with leap seconds would be counted as having 86401 seconds instead of 86400 seconds. This is not the case. In the example you cite, the Unix time resets to 915148800 after the leap second (1999-01-01T00:00:00), so the leap second isn't counted. Unix time differs from the true number of seconds since the epoch by the number of leap seconds (plus the UTC-TAI time difference between 1970 and 1972, before leap seconds were introduced).
- habibur 4y agoC needs default parameters. Where the compiler puts on stack the default value, whenever the function call doesn't include it. Guess that won't compromise with anything.
- JonChesterfield 4y agoHow would you have those work with function pointers?
- habibur 4y agoGood point.
- kangalioo 4y agoI see the point. Out of curiosity, I thought up some approaches: - disallow making function pointers of functions with default params - require explicitly passing all params when used as a function pointer - generate a trampoline function that generates the default params and use that as the function pointer - somehow include the default param values as part of the function pointer type
- unwind 4y agoWouldn't that be just as hard as for any other function? The name of a function (a bit like the name of an array) evaluates to basically a function pointer value, there is little difference between the two calls here: int foo(int a, int b) { return a + b; } int main(void) { printf("Direct: %d\n", foo(1, 2)); int (*ptr)(int, int) = foo; printf("Indirect: %d\n", ptr(1, 2)); return 0; } of course default arguments, if added, would have to be part of the function pointer type as well, making the above: int foo(int a = 1, int b = 2) // NOT REAL CODE, FANTASY SYNTAX { return a + b; } int main(void) { printf("Direct default: %d\n", foo()); int (*ptr)(int a = 1, int b = 2) = foo; // NOT REAL CODE, FANTASY SYNTAX printf("Indirect default: %d\n", ptr()); return 0; } Unnamed function arguments would look silly (`int (ptr)(int = 1, int = 2)`?), but I would be radical then and only support default argument values for named arguments, probably. Edit: fixed a typo in the code, changed in-code comment.
- g0xA52A2A 4y agoPrevious discussion https://news.ycombinator.com/item?id=33691048 https://news.ycombinator.com/item?id=33691048
- tempodox 4y agoInteresting and very welcome improvements. Can't wait to get my hands on a full C23 compiler.
- sgt 4y agoFor a new project in C going forward, will it makes sense to usr C23?
- ainar-g 4y agoDepending on your definition of “using”, you may not actually be able to, at least for now. If CPPReference's table[1] to be believed, there are still important features that are either missing from GCC and Clang or implemented “partially”, which may mean different things for different features and compilers. In my personal opinion, unless you're doing the project just for fun, it seems better to stick to C11/C17, at least for the next few years. [1]: https://en.cppreference.com/w/c/23#C23_core_language_features https://en.cppreference.com/w/c/23#C23_core_language_feature...
- m-ee 4y agoIn the embedded world it’s still a struggle to get people to use C99, maybe in 20 years for us.
- vkaku 4y agoYes. The idea behind most of the stuff seen in C23 is to rid itself of UB that ultimately lead to easier to maintain better compilers and libraries. While in practice it may take long for some things to follow the standard, it is certainly a step in the right direction. This is my humble opinion.
- MattPalmer1086 4y agoGlad to see memset_explicit for zeroing out sensitive data.