13 ms·
C23 is finished: Here is what is on the menu
- rwmj 4y agoIt's a shame that attribute((cleanup)) wasn't standardized since it's very widely used in real C code, but at least the badly designed and massively overengineered "defer" suggestion was rejected.
- pjmlp 4y agoWidely used in GCC C code.
- rwmj 4y agoIt's supported by Clang, so widely used in open source projects - systemd, libvirt, everything using glib, some Linux kernel tools, dracut, qemu, glibc, ..
- pjmlp 4y agoApparently, no one has bothered to update clang´s documentation on that regard, https://releases.llvm.org/14.0.0/tools/clang/docs/AttributeReference.html https://releases.llvm.org/14.0.0/tools/clang/docs/AttributeR... Many of those open source projects happen to only compile with GCC, exactly because they rely on GCC C. Google has spent several man years making the Linux kernel compilable with clang, and not all of it has reached upstream to this day.
- rwmj 4y agohttps://clang.llvm.org/docs/AttributeReference.html#cleanup https://clang.llvm.org/docs/AttributeReference.html#cleanup. We use it in several projects and compile those with clang. Here's nbdkit compiled with clang 14: https://gitlab.com/nbdkit/nbdkit/-/jobs/2814022460 https://gitlab.com/nbdkit/nbdkit/-/jobs/2814022460 checking whether clang is Clang... yes [...] checking if __attribute__((cleanup(...))) works with this compiler... yes
- pjmlp 4y agoThanks for the example.
- loeg 4y agoYes, Clang is pretty bad about updating their documentation of GCC features they support.
- ndesaulniers 4y ago> and not all of it has reached upstream to this day. Which parts haven't? Asking as the project lead.
- pjmlp 4y agoAs far as I can tell, only Linux Android compiles cleanly out of the box with clang, not so with regular Linux kernel. At least that is my impression from occasional Linux talks. By the way what's up with NDK, Android packages, and that roadmap with better C++ development? Thankfully no longer a problem of mine.
- ndesaulniers 4y ago> not so with regular Linux kernel. $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git $ cd linux $ make LLVM=1 -j$(nproc) defconfig all -s $ echo $? 0 $ See also the official kernel docs which describe more which architectures can be expected to compile cleanly out of the box. There are something like 10^6000 possible kernel configurations though, so no promises (regardless of toolchain). https://www.kernel.org/doc/html/latest/kbuild/llvm.html#supported-architectures https://www.kernel.org/doc/html/latest/kbuild/llvm.html#supp... We support clang-11 and newer. Linus Torvalds has been using clang to build the kernels he runs personally, for ~2 years now. https://lore.kernel.org/lkml/CAHk-=wiN1ujyVTgyt1GuZiyWAPfpLwwg-FY1V-J56saMyiA1Lg@mail.gmail.com/ https://lore.kernel.org/lkml/CAHk-=wiN1ujyVTgyt1GuZiyWAPfpLw... >> I build the kernel I actually _use_ with clang, and make sure it's clean in sane configurations Not sure what's going on these days in Android land, thankfully no longer a problem of mine.
- pjmlp 4y agoI stand corrected, and apparently the love for the NDK experience goes both ways.
- AlbertoGP 4y agoI added one of those features, #embed, to my Cedro C source code preprocessor and posted about it yesterday: https://news.ycombinator.com/item?id=32341326 https://news.ycombinator.com/item?id=32341326 Here is the direct link: “Use #embed from C23 today with the Cedro pre-processor” https://sentido-labs.com/en/library/cedro/202106171400/use-embed-c23-today.html https://sentido-labs.com/en/library/cedro/202106171400/use-e... As I write there, “The advantage of using Cedro is that the source code is the same and this way it is very easy to use different compilers, only adding or removing the #pragma line.” I also added a command-line option to embed the bytes as strings instead of byte literals; embedding an 8 MB file, the strings variant compiled between 28 and 72 times faster depending on which compiler I used, gcc or clang. It is more efficient, but less compatible, that’s why it’s optional. I’m considering adding some low-hanging fruit, like the number literal separators: 1'384'849 → 1384849
- kibwen 4y agoFor number literal separators, I'd suggest using underscore rather than apostrophe. Ada, C#, D, Haskell, Java, Kotlin, OCaml, Perl, Python, PHP, Ruby, Go, Rust, Julia, and Swift all use the underscore. C++ wanted to use the underscore, but was forced to use the apostrophe because of user-defined literals.
- AlbertoGP 4y agoYes, I meant implementing it as specified for C23 which was done for compatibility with C++, although I do prefer the underscores. Maybe that’s a better idea, implement it with underscores in Cedro as it does not need C++ compatibility. Edit: alright, it works. I also extended the parser to accept the apostrophe as part of number tokens. The only thing it does is to remove the underscores when writing. I might need another command line option to specify whether the output should be C23: 1_234_567 → 1'234'567 or pre-C23: 1_234_567 → 1234567 1'234'567 → 1234567
- EdSchouten 4y ago> N3020 - Qualifier-preserving Standard Functions I just read the actual proposal on it. They describe an example implementation using macros and _Generic. What’s really bad about this is that the arguments provided to these methods are used more than once in the macro body. This will cause: - gibberish compiler errors in case of typos in the arguments, - worse compilation times, as the compiler has to process more code. Constructs like these may lead to an exponential explosion in preprocessed source code size. I hope that nobody implements it that way.
- jonathrg 4y agoHow exactly can this lead to exponential explosion?
- pdw 4y agoCode that does things like strcat(strcat(strcat(strcpy(...), ...), ...), ...)
- jonathrg 4y agoIf I understand the implementation section of the proposal correctly, the preprocessor will just add ome cast to (const char*) per function call (assuming the innermost argument is const). Nothing exponential
- lifthrasiir 4y agoFor the ease of discussion here is the relevant piece of code: #define IS_POINTER_CONST(P) _Generic(1 ? (P) : (void *)(P) \ , void const *: 1 \ , default : 0) #define STATIC_IF(P, T, E) _Generic (&(char [!!(P) + 1]) {0} \ , char (*) [2] : T \ , char (*) [1] : E) #define _STRING_SEARCH_QP(T, F, S, ...) \ STATIC_IF (IS_POINTER_CONST ((S)) \ , (T const *) (F) ((S), __VA_ARGS__) \ , (T *) (F) ((S), __VA_ARGS__)) #define memchr(S, C, N) _STRING_SEARCH_QP(void, memchr, (S), (C), (N)) #define strchr(S, C) _STRING_SEARCH_QP(char, strchr, (S), (C)) #define strpbrk(S1, S2) _STRING_SEARCH_QP(char, strpbrk, (S1), (S2)) #define strrchr(S, C) _STRING_SEARCH_QP(char, strrchr, (S), (C)) #define strstr(S1, S2) _STRING_SEARCH_QP(char, strstr, (S1), (S2)) Here `IS_POINTER_COST` expands `P` twice so `_STRING_SEARCH_QP` expands `T`, `F`, `S` and each variadic argument 2, 2, 4 and 2 times respectively. Note that only `S` and variadic arguments are expressions and evaluated only once, but the number of expanded tokens can blow up exponentially.
- Aissen 4y ago> memset_explicit Exciting to see this in the standard. Once this is in all compilers, this will probably have security effects beyond C. Fun fact: Miguel Ojeda linked to @cperciva's article and its following HN discussion in the note (N2897) to propose this: https://news.ycombinator.com/item?id=8270136 https://news.ycombinator.com/item?id=8270136
- Sakos 4y agoI'm not familiar with C at all, but I'm wondering why they chose to add a keyword just for this specific case instead of providing a way to granularly tell the compiler not to optimize specific lines of code or what optimizations are permitted.
- Aissen 4y agoI'm guessing that this would have been either too complex, or taken too many years. The pragmatic, lower scope approach, already required quite a lot of work.
- Jensson 4y agoVolatile is exactly for this case. If you write or read a volatile variable then the compiler isn't allowed to remove the operations for any reason.
- 1ris 4y agoThat's what i thought, but apparently this is wrong. Had a disscussion about this here: https://news.ycombinator.com/item?id=27804810 https://news.ycombinator.com/item?id=27804810
- Jensson 4y agoI don't believe they are correct, or at least their arguments doesn't explain why it wouldn't work. Volatile wouldn't work with memset since memset doesn't take a pointer to volatile memory, that is true, but you could set the volatile data yourself and it shouldn't be optimized away as per the spec. The data living on a stack doesn't matter, it works perfectly fine having volatile data on the stack. I tried the following code in a few compilers, it works perfectly for overwriting buffer pointers that goes out of scope, also tested removing the volatile to ensure that the memory write was ignored and I reproduced the code vulnerability where the previous message was still there the second time I tried to read a message, and from the way I read the spec this shouldn't be optimized away by any compiler: void memset_explicit(char* p, char c, size_t n) { volatile char* vp = p; while (n--) *vp++ = c; } Casting other data types to a pointer to volatile data is within the spec, and the compiler should then treat it like any other volatile data.
- flomo 4y agoI really don't know any C beyond K&R years ago, but this was an enjoyable read.
- tialaramex 4y agoProbably worth clarifying whether you actually mean the Second Edition of Kernighan and Ritchie's book "The C Programming Language" which is about ANSI C and thus approximately ISO C89, or you literally meant what is called "K&R C" the language described in the 1978 edition, by the same name, which is a language somehow composed entirely of sharp edges.
- convolvatron 4y agoand cute post/pre increment/decrement tricks!
- hbn 4y agoI started reading through/doing the exercises earlier this year and I noticed there was a lot of "cute" tricks in their code examples, such as loops that perform functionality that's all defined in the control flow definition (init/condition/increment) of a for loop, and instead of a loop body it's immediately followed by a semicolon. Perhaps they're just to give you a better understanding of the more minor details/intricacies of the language, but I couldn't help but think with a lot of their code, if I saw a coworker write something like that I'd roll my eyes that they didn't do it in a more obvious way.
- tialaramex 4y agoI think that the way K&R writes C is probably idiomatic C just de facto. But it's also reasonable to believe this style is completely unacceptable for maintainable code today and should fail review for example. So, it's not crazy to argue that because idiomatic C isn't acceptable therefore rule out C as a language for an organisation to use entirely. Clearly if you don't have an alternative this highlights a problem rather than itself being a solution. But it might be a reason not to do whatever it was you were thinking of doing at all. Do you really need to write micro-controller firmware for your project? Isn't there an off-the-shelf component where it's not your problem to maintain the horrible C code that makes it work? [ Or you could go all Oxide Computer Company and decide no, C is just terrible so we are going to use Rust and if we need to rewrite the firmware on this switch that's what we'll do. That might make total sense, if you go into it clear eyed ]
- forrestthewoods 4y ago> We do not have namespaces in C, which means any time we add functionality we basically have to square off with users. Has anyone seriously proposed adding namespace to C? This feels like an obviously good addition to me. What’s the argument against it?
- raverbashing 4y agoI'm skeptical of it. I think it is a std::opinion::bad_idea() ;)
- mgaunard 4y agomaybe we could call the language with such extensions "C++"
- mort96 4y agoExcept that C++ doesn't serve that role, C++ is its own whole thing. I think "C but with namespaces and a method call syntax (and templates?)" would be a great language which would occupy a completely different space than C++.
- jcelerier 4y agoif you introduce namespaces and method calls you have to introduce name mangling, to differentiate namespace foo { void x(); } and namespace bar { void x(); } and then you have to rely on compiler vendors to use the same mangling everywhere otherwise you end up exactly at the C++ position where there are multiple incompatible name mangling schemes, thus C code compiled with e.g. cl.exe would not be able to call a C function compiled with gcc (and FFIs wouldn't be able to either so you loose the "easy language bindings" "feature" of the operating system ABIs)
- jstimpfle 4y agoNamespaces by themselves aren't a reason why name mangling is needed. There isn't a technical reason why foo::x couldn't be the symbol name, literally. (Not sure what ELF and PE/COFF etc would think of these names in current implementations). Name mangling is needed if you want to overload functions and qualify them only by the types (not names) of their in and out parameters. This is where it gets ugly on the binary level.
- Sakos 4y agoFor anybody else who has no idea what C23 is and for whom the article's intro really wasn't helpful, this is about a proposed major standard revision for the C language (https://en.wikipedia.org/wiki/C2x https://en.wikipedia.org/wiki/C2x).
- teddyh 4y agoWhat will the __STDC_VERSION__ be?
- jwilk 4y agoThe current draft says 202311L. But I guess it's not set is stone yet?
- teddyh 4y ago> N2888 - Exact-width Integer Types May Exceed (u)intmax_t This creates a problem. How do you portably printf() an integer type that you don’t (and can’t) know the size of, like, say, a uid_t? Before, when intmax_t was guaranteed to be the largest type, you could reliably and portably cast a uid_t userid to an intmax_t and printf() that: printf(PRIdMAX "\n", (intmax_t)userid); But now, when any type might be larger than an intmax_t? What do you do? (The same problem exists when reading an integer string; how do you read, say, a port number, when you don’t know what type in_port_t is? Previously, you could call strtoimax() on the string, detect overflow, and then cast the resulting intmax_t to in_port_t and finally compare for equality to make sure it wasn’t truncated.) > There is active work in this area to allow us to transition to a better ABI and let these two types live up to their promises Yes please. Introducing new wider integer types in your CPU, but pretending you haven’t created a new architecture with an associated new ABI, is silly.
- formerly_proven 4y ago> But now, when any type might be larger than an uintmax_t? What do you do? Complain to POSIX so they add printf macro defines for all their implementation-sized integer types by the year 2100.
- teddyh 4y agoFor printf(), that would work. For sscanf(), POSIX could add macros there, too, but sscanf() does not detect integer overflow. That’s why the only previous solution was strtoimax() which does detect overflow.
- rwmj 4y agoscanf not detecting integer overflow is arguably another problem. It's usually the easiest way to parse numbers out of simple strings, but the lack of overflow detection is a problem. (Actually we use sscanf for this and ignore the overflow problem, as long as it doesn't cause any security or correctness concern.) IIRC glibc actually does overflow detection, so there's not anything inherently problematic with adding it.
- Kukumber 4y agoThey really want to kill C right? If you want a better C, do yourself a favor and use D Same syntax, more secure and with modules
- Xunjin 4y agoThis kind of comment is not helpful at all, I use Rust today however, yet I cannot sometimes deny, it's better to use C depending on the target and restrictions by hardware compilers. Every language has downsides/upsides and time. There is a nice quote by Titus Winters: “Engineering is programming integrated over time”[0], this helped me a lot in learning that context matter for tools/languages/frameworks, and you can learn with their mistakes. [0]: https://youtu.be/tISy7EJQPzI https://youtu.be/tISy7EJQPzI
- Aardwolf 4y agoWhich change in particular do you dislike?
- Kukumber 4y agoIt's not about things i dislike, it's subjective, it is about their priority and the feature they think are needed I'm still waiting for tagged unions, tuple and pattern matching auto and #embed is nice to have though
- __phantomderp 4y agoI don't think we have any proposals for language-supported tagged unions (have to do them yourself), tuples (write your own macro/struct), or pattern matching (lole). You'll have a hard time pushing for those: C will likely never get them in those forms. At least, not for another 10-20 years, since there's no existing C compiler that implements any of those things yet.
- Kukumber 4y agoThere you highlighted what i meant by they want C dead
- qalmakka 4y agoWhat saddens me is that this is yet another missed opportunity for fixing the C strings library, which is sadly mostly broken beyond repair or straight unusable on modern systems. Annex K tanking badly was just sad. At least they finally standardized strdup().
- fanf2 4y agoAnnex K is appalling. It depends on global shared mutable state, so it is incompatible with threading.
- jstimpfle 4y agoHow do you intend to fix the strings library? beyond strlen() and _maybe_ the search functions like strchr() there really isn't much you should use. And those functions are _fine_. Some of the string functions, like strtok() or strcat(), and I would also include strdup(), are broken beyond repair and should simply not be used. The only way to "fix" the library would be to remove these functions, but I assume this would create more trouble with legacy code than it's worth. C strings are mostly a useful storage format for small strings, including string literals, and as a "default" string type for the little basic functionality that is expected to be part of C to support a small program growing up - including printf() and friends. For longer strings, you are expected to build datatypes that fit your usecase, and that includes decisions about memory management. It should not be the responsibility of the language to make these decisions for you.
- Bigpet 4y agoI'm just happy that both C and C++ now have bit stuff like byteswap, popcount, rolr, etc. It was a bit silly that stuff like that wasn't in either standard until this recently.
- quelsolaar 4y agoThese this are much more complicated to define then you think when you consider the kinds of strange hardware C supports, where bytes are not 8 bits and things like that. We tried to get endian-ness conversion functions in to c23 but ran out of time just because defining these functions so that their functionality is clear on non standard hardware is so difficult.
- fanf2 4y agoIt would have been reasonable to define the functions only for the CHAR_BIT == 8 case, and if any implementers that support weird architectures want the functionality let them come forward with a proposal. I got the impression that the people working on the proposal got into an avoidable mess of complications.
- quelsolaar 4y agoGiven that weird platforms are so dependent on C and since we release versions so infrequent, we try to get it right the first time. Often even defining what is excluded becomes complicated.
- cbrogrammer 4y agoif C throws away portability it is no longer C
- pjmlp 4y agoC's secret to portability is called #ifdef spaghetti and mostrosities like autoconf.
- Bigpet 4y ago
- hgs3 4y ago> N3042 - Introduce the nullptr constant They should have formally defined NULL as void* instead. > Someone recently challenged me, however: they said this change is not necessary and bollocks, and we should simply force everyone to define NULL to be void*. I'm glad someone brought it up. The scenarios nullptr "fixes" are so minor adding a new null concept to fix them is the sort of overkill solution I expect from the C++ committee, not the C committee. It's a shame this wasn't thought-out more. > I said that if they’d like that, then they should go to those vendors themselves and ask them to change and see how it goes. The C committee has already broken compatibility on numerous occasions: forcing 2's complement representation, changing the type of u8"" string literals from char to unsigned char, removing mixed wide string literal concatenation (allowed in C11, disallowed in C23). It's difficult to be convinced by the argument of backwards compatibility when the committee has already broken it on multiple occasions. Furthermore, I seriously doubt compiler vendors who define NULL as 0 would take issue with redefining it as void*. This change is so minor and inconsequential there should be no push back.
- stonemetal12 4y agoI am not all that standards savvy, so pardon my ignorance. >Introduce the nullptr constant >They should have formally defined NULL as void* instead. That doesn't make any sense to me. void* is a type isn't it? nullptr is a value. I don't see the overlap.
- hgs3 4y ago> That doesn't make any sense to me. void* is a type isn't it? nullptr is a value. I don't see the overlap The C standard permits NULL to be defined as (void*)0 or 0. The issue is this creates an inconstancy when NULL is used with _Generic selection: a compiler defining NULL as (void*)0 will cause NULL to be caught by a pointer case whereas a compiler defining NULL as 0 will cause it to be caught by an integer case. This inconsistently could be solved by mandating NULL be defined as (void*)0 so it will always be caught by the pointer case. The issue is instead of mandating (void*)0 the C committee decided to introduce a whole new nullptr concept. This duplicates the concept of null in the language and requires all C compiler vendors to modify the languages type system to account for it. So it creates more work for vendors and duplicates the concept of null all to solve this minor use case.
- macintux 4y agoExtensive discussion about #embed a couple of weeks ago. https://news.ycombinator.com/item?id=32201951 https://news.ycombinator.com/item?id=32201951
- rando14775 4y agoWhen will they add a slice (fat pointer) type? I.e. a generic version of > struct T_slice { T* ptr; size_t len; }; with all the syntactic sugar and bounds checks added in. This could catch so many out of bounds issues and doesn't seem that hard to do.
- axus 4y agoThe author listed "wide pointers" in the second paragraph of things they are impatient for, and would like a faster release cycle for. It sounds like it could be another 10 years.
- __phantomderp 4y agoThe original authors of the language also advocated for this, and Walter Bright's D compiler has a BetterC compiler that also includes a int arr[..]; syntax for such things. But, our plates are full and the proposal wasn't written: it'll be up for next release, for sure, and it's one of the many things I would like to put in the language.
- TheBrokenRail 4y agoI am so glad to see #embed. I always thought it was silly that the best way to embed a resource in a binary using CMake was to either convert it to hexadecimal C array manually or use specific flags with ld to convert it into an object (and good luck getting that to work reliably with cross-compiling!).
- JonChesterfield 4y agoI'm pleased by making types with the same tag and fields compatible within a TU. That was a stupid thing to work around with offsetof. Unfortunate characterisation of constexpr in C++ over revisions as feature creep. It's more that any C++ should be executable at compile time with constexpr ultimately going the way of the register keyword, but selling people on things like compile file I/O is a long game. Ultimately though it's hard to be too excited. I don't have a use case for C any more, beyond keeping some old code alive (with fstrict-aliasing et al and a sense that I really should port it to something else before I can no longer get any compiler to build a program out of it).