95 points · by marcobambini · 4y ago · 173 comments
I liked C in the 80s, 90s and 2000s. It was a neat and simple language, but that changed as compilers got more aggressive with their optimizations and exposed just how complicated and unintuitive the spec actually is (and the impossibility of avoiding UB). C was a good learning experience for language committees (as was C++), but it's time to cut our losses and move on.
I also liked C++ in the 90s, but soon grew to despise it. When they tried to revamp it and make it safer to use, I was hopeful, but that's now gone. It's too complicated, the error messaging sucks, and there are too many different ways to do the same thing (with ever changing best practices). In a way, CMake and C++ are two peas in a pod.
This is why I now pin my hopes on rust and zig. I want to write low level code, but not in C or C++. I want a build system that's not Makefiles, CMake, or (shudder) gradle.
Indeed, this is one of the two things where C is still king, the other being running on weird hardware with specialized compilers.
That said, C is not a great glue language:
- Zero terminated strings are only used in C so every other language needs to do a copy to pass a string to C, even C++ (for string_view at least).
- A lack of fat pointers means that buffers need to pass their pointer and length separately, which is awkward, or use a custom struct which other languages will know nothing about.
- It has no standardized error handling mechanism to help with writing automatic wrappers on the other language endpoints.
- It has no modules or namespacing.
So while C will continue to be the glue language of the programming world, I wish it was just a bit better than what it is, would make language interoperability a lot nicer...
I don't think that's what he's talking about. No matter what glue you had, you need to pass NUL terminated strings to C code that uses NUL terminated strings.
The glue interface does not require any such thing though.
> A lack of fat pointers means that buffers need to pass their pointer and length separately, which is awkward, or use a custom struct which other languages will know nothing about.
Again passing things between two languages will always necessitate that. One language might have a different fat pointer implementation than another.
And the nice thing about glue code is that it can be easily automatically generated calling wrappers so "awkward" does not come into it - you change one language's data types into another's.
> - It has no standardized error handling mechanism to help with writing automatic wrappers on the other language endpoints. - It has no modules or namespacing.
I don't see how this matters for the interface glue. You can define the error handling with it how you like. You put it in your language's namespaces and modules.
Rather, languages like Rust/Zig/C++ and even C# and Java let you expose a C API such that other languages can understand the shared library as if it was written originally in C, because C is the only thing every other language talks.
By necessity this involves using standard types available in C otherwise the other languages have nothing to go on, they'd just have a bunch of opaque types and no way to create them.
If C had better builtin constructs, these "extern C" APIs could be much better semantically, such that automatically generating wrappers to this C API would result in safer, more efficient, and more ergonomic code in the host language.
1. C headers are exceptionally annoying to correctly parse and interpret. You basically have to have a full C compiler, which is a PITA for a non-C tool. It's not just complexity of the C syntax, but dependency on system headers, implicit platform-specific type sizes and struct layouts, and an arbitrary web of ifdefs which may need to be generated by an arbitrary build system. Everything here resists automation, and if you get any details wrong, you won't know until you see memory corruption.
2. The common baseline between most programming languages has outgrown what C can express. Namespaces and other name mangling, unwinding, non-nullable types, slices, ownership/destructors, thread-safety annotations, etc. C++ has some of these features, but it solves none of the above problems, and only adds more complexity and its own compiler-specific behaviors.
This is one of the most frequent complaints and I find it ridiculous. C has string literals that encode zero-terminated strings, but you don't have to rely on these zero terminators. There are a few awquard "string functions" in libc, most of which you should just ignore. Besides maybe the printf() family (which you probably wouldn't want to use for interoperability there isn't anything that requires zero-terminated strings.
This language gives you memory to work with, and it's up to you how you want to achieve your goal.
> A lack of fat pointers means that buffers need to pass their pointer and length separately, which is awkward, or use a custom struct which other languages will know nothing about.
It could be considered a security problem that sizes have to be passed separately, but what I consider awkward is actually the slices approach: In general the count field in a "slice" is redundant data - think about parallel arrays, where with slices you need to synchronize the count information across all slices. Passing separate length is the correct approach from a normalization standpoint.
> It has no standardized error handling mechanism to help with writing automatic wrappers on the other language endpoints.
Similar to the point about slices, not including any notion of "errors" is the correct way of doing it. In general you don't want errors in a system, only data that you handle in an appropriate way. Also, returning what people usually consider errors is often a bad idea, as such error information should better be stored in a persistent handle or context struct.
> It has no modules or namespacing.
Not a problem, since there are names that you can already use for disambiguation. Namespaces only add more ways to identify the same object, which leads to ambiguity and/or hard to read and hard to grep code. (Namespaces encourage the use of not-fully-qualified identifiers - actually this is the only thing they really add, and apart from some metaprogramming tricks you can play I don't think it's a great addition).
And yes, as a library developer you need to signal errors somehow, and whichever solution you use, the binding generator doesn't know about it. Rust has a nice error propagation mechanism which lets me attempt a set of operations but abort early when an error happens, but the binding generator can't use it.
Namespaces are a similar problem, they force library devs to try and come up with unique but short prefixes. Had C had namespaces the "short" constraint wouldn't be a problem, pretty much eliminating the chance of collision.
Am I right in assuming you're an embedded developer? Typically when I have this discussion with people the points that you make come from embedded devs. They're not reflective of the needs of library developers.
Just a quick question. Is there somewhat up-to-date guide, list, book, whatever of good best practices for C, or maybe small libs for simple string handling, and common pitfalls (checking for over/underflows etc.)?
That's one of the issues in most UNIX systems. Windows sidestepped it with COM (and a much improved WinRT as a successor, with a .NET-y object model). On Apple systems, Obj-C is pretty much usable from other languages too, being the standard ABI to glue it all.
My takeaway: bring one of those two options properly to Linux, which is needed hard by now, to not fall to the lowest-common denominator.
(C++ isn't a solution because of a dubiously stable ABI on quite some platforms)
Erm, isn't the whole point of COM that it is also just a "C glue interface"? Not how one would typically design C APIs, but COM APIs are C APIs nonetheless.
You forgot mainframes or even Android (C ABI without JNI is of not much help), or ChromeOS (WASM yeah).
Linux has such an option, D-BUS, now adopting it at scale is another matter.
If C++ would just treat C as an interface like everyone else does, this problem would shrink considerably.
That wasn't possible anymore from the moment on when C++ decided to not treat C as a proper subset (like Objective-C did), but instead fork its C subset into a slightly different language.
Humans are stupid, short-sighted creatures, and programmers are no exception. The only way to get C programmers to use C++ was to make C-with-classes a drop-in replacement for C. Replace "cc" by "CC" in your build system, and you magically get new features, without breaking old code (at least not too much). Sure it crippled C++ from the start.
If C++ had stopped at binary compatibility (either with an FFI like Rust or Zig, or by deciding on a subset that can talk to C interfaces), it would have forced users to use two compilers, as well as learn an entire new language. Few people would have been willing to put in the work, Stroustrup knew this, and he wanted his language to be useful now.
And now we have this mess.
So in many cases, although a better solution exists, many devs will code C+ unless forced to do otherwise.
Objective-C suffers from the same problem.
For the two decades I've used C, I've not had a compiler that resembles "portable assembly." The unoptimized code they generate is extremely naive and far removed from anything an assembly programmer would write, easily resulting in many times more instructions than a simple & straightforward assembly implementation. As one might expect, the performance of such code is atrocious.
With gcc and clang, optimizations are absolutely mandatory if you want compilers to generate anything resembling good assembly. And it is still an uphill fight to avoid silly code. Just last week I scratched my head because gcc insisted on recreating a constant that is already there in a register, in that very same register it is recreating it in [1]. You could force it to keep the value in a register by creating a top level variable and use the asm("register") extension, but that just resulted in gcc making copies of that value into other registers.
Also worth pointing out that there's a lot of stuff in assembly that you cannot express in C directly. You want a rotate instead of two shifts and OR? You absolutely have to have an optimizing compiler, because rotate does not exist in C. Want to shift and test carry? No, that is not possible in C. Compiler extensions give you access to some things (e.g. popcnt) but the vast majority of assembly is only achievable indirectly by assuming the compiler can optimize your code and figure out what instruction you want. Also those extensions hardly make it portable..
I also think the vast majority of C code I see looks very different from assembly; it is written under the assumption of an optimizing compiler, which converts idiomatic C to somewhat idiomatic assembly.
But by god I love C. I use C for most of my library interfaces so that I can easily make C++, Python, etc versions in more pleasing versions for those languages. It's much, much easier to work from C and to another language than it is to cross language boundaries laterally.
That probably won't change, so I'll always use C at least a little bit when building tools.
In that respect, C is still winning. It's upstream of everything, easy to compile, and has libraries for everything.
It’s tricky to balance features, backward compatibility and ‘cleanliness’ in a (language, standard library)
Even so, one example in C++ where it's almost impossible to avoid UB is treating a piece of memory as both a struct and raw bytes with guarantees of no copying. This comes up a lot in network packet processing.
But for an entertaining read, there are some fun stories floating around about Linux vs GCC with the kernel devs resisting compiler optimisations, and even holding back the "supported compiler versions" over it :)
I have this controversial thought: C people understood one thing before everyone else (including the creators of C++, Rust, and any other language), and is this:
“Perfection is Achieved Not When There Is Nothing More to Add, But When There Is Nothing Left to Take Away” -- Antoine de Saint-Exupery.
Super-bloated languages that keep adding features every month/year are far from perfection.
Now bring it on!
Note: I love both C and C++. I prefer C because it's simpler (I write firmware for a living). Sometimes I use C++ with simple classes and I might throw in a template or two if I am in a good day. Of course my classes are for my use only: don't try to copy/move them!! I won't chase every little nitpick of deleting and overriding every operator/constructor!! And the further I might go is implementing a Singleton.
Thanks and have a great day!
A device driver, on the other hand, can be implemented in software or firmware, or, usually these days, as a combination of both. Drivers indeed are magic - since they usually designed to interact with, and to control, physical systems, they must work in real time, and writing a driver requires understanding the system's behavior to a minute detail.
https://en.wikipedia.org/wiki/C17_(C_standard_revision)
"C17 addressed defects in C11 without introducing new language features" means a lot.
https://en.wikipedia.org/wiki/C2x
Has a few additions compared to C++20 (https://en.wikipedia.org/wiki/C%2B%2B20)
https://news.ycombinator.com/item?id=30160590
Also you forgot the endless amount of compiler specific language extensions.
If I only need (as is 99% of the time the case) a smidge of code to run nanosecond-fast, I'd write a C extension and call it from a higher-level language that does the orchestration code. The C extension would by definition be simple code, so there is no real problem with C as such - it's ideally suited for that role.
Only in the rare case that a large program needs to be nanosecond-fast would I even consider C++ (and I'd push really hard to learn if that really needed to be true!), and then I'd write code like it was 2003 - smart pointers and POD classes, but that's it. The new libraries are wonderful for saving code and getting good fast implementation of algos!
This is mostly true for web development where bottlenecks just exist in IO and beyond. For gaming this is not the case. The entire industry needs nanosecond latency so engines must be written in languages that are nanosecond-fast.
Anyway, some things I think would make for interesting content at such a conference, should one decide to exist:
Modern C. It would be useful with practical down-to-earth comparison between C the way (I feel) many think it "should" be written, i.e. C89-style with lots of worry that the compiler may be broken, and something more modern/sensible.
Standard directions. Some kind of survey-style talk trying to both summarize known interests covered by the committe now, and also perhaps polling the audience for input about where C needs to go.
Compiler architect's thoughts. Get the major compiler writers in a panel, have them talk about how various language (mis)features affect their ability to write good compilers, and what changes would help with that, if any.
Code sight-seeing. Just having a few knowledgable folks navigate some well-known codebases on a projector with commentary/analysis would be very interesting I think, both to see how others have solved things, and perhaps spot problems/possible improvements. Must be done respectfully of course.
Now I almost feel as if I miss that conference. :/ More ideas, anyone?
(Edited for typos and grammar)
There doesn't need to be a conference for everything under the sun. I don't see a screwdriver conference popping up around me anytime soon.
* https://youtu.be/YnWhqhNdYyk
And also talks promoting proselytizing to C programmers and bringing them to C++:
* https://youtu.be/D7Sd8A6_fYU
And of course, now, Rust is supposed to supplant C.
That's shocking to me. But this goes along the fact that C on the web is scarce..
> Code sight-seeing
I would love to attend such C workshops.
No, what I mean is these subtle things that are impossible to get right: stupid integer promotion rules, needlessly complex declarations, messy stdlib functions, undefined behaviour as a feature, etc.
For all its faults, there's much less churn in the definition of C and what change does occur seems to be driven by clearly demonstrated needs out in the real world. C might seem stagnant, outdated, incomplete, or unsafe - all fair criticisms - but at least a competent C programmer's hard-won knowledge of how to overcome these deficiencies doesn't get turned on its head every few years as a new language version comes out. Even decades-old C (at least since the K&R vs. ANSI function-declaration change) is still readable and scarcely less idiomatic than something written last week.
So, referring to the OP's title, which language has the bigger problem?
Because my takeaway from the article is this: C++ piled loads and loads and them some loads of stuff onto a slim, easy, comprehensible language, is now a gigantic pile of complexity. that has precious little to do with its roots any more...and every attempt to solve its problems includes piling on more complexity.
So, how is that a problem of C?
C is not responsible for C++, simple as that.
I don't understand why this is a C problem, whose syntax and definitions have been relatively stable for the last 3 decades. Author has gripes with C++ 'universality' IMHO but just piling it on C.
Because it isn't a C problem. C has been basically stable for decades.
C++ is free to overload itself by piling ever more stuff onto itself, but any problems this language has, are not problems of C, or problems C needs to fix.
Microsoft's 2012 advice [1] to compile C code with a C++ compiler was misguided (at the time this was just an excuse to not support the latest C standards in MSVC). Writing C code in the so-called "common C/C++ subset" is a massive PITA for a C coder, because this common subset is a nonstandard dialect of C which will forever be stuck in the mid-90s.
[1] https://herbsutter.com/2012/05/03/reader-qa-what-about-vc-an...
The only major problem with C is its community never took off with a popular library packager and linter. Every other language that seems so cool today would be just as painful as C if they didn't have so many contributed modules and tweaks. Port those to C and people would fall in love with it all over again.
Does anybody have background information on this claim? Was there actually a working compiler with it back then or was it just some proposal paper at the time?
Look for Bjarne talks at CppCon on the subject of language evolution, he has mentioned it on a couple of them.
Only used ANSI so wondering what excellence of K&R C mean
At least with cfront you had some idea of what was getting generated.
My favourite C++ compiler was Symantec 7 on windows. It was a great, affordable tool for making MFC applications and had a neat GUI builder too. I still have the CD of it but it refuses to install on windows 11 sadly.
Nowadays I just use C or C#, C++ just seems like a hard to use version of C# and I have little use for the extra performance it might have.
Specifically the somewhat recent idea that code which does something naughty is best deleted. This makes updating a compiler a hazardous activity for approximately all 'C' code. Also makes refactors somewhat risky when they send code down different paths in the compiler.
I wonder if this judgement and execution result from collaboration with C++.
So I guess you like Fortran77?
C structs can already do most of what C++ classes can do. Including inheritance and virtual methods, when you really really need them. As for encapsulation, pointer to implementation provide a more stable, harder to cheat interface than private members. A must for stable ABIs.
C does lack generics, and I do often miss them, but templates really aren't a good solution. I don't know what a good solution looks like, I haven't looked at Zig or Rust yet.
Another thing I miss in C is a namespace system, especially when you ship libraries: makes every name longer, and you still have annoying name clashes from time to time.
No. They're not. References must point to valid objects (i.e., cannot be nullptr and cannot be random addresses in memory), and you cannot do arithmetic on them. They are much safer to use than pointers, so actually, references make pointers redundant.
> C structs can already do most of what C++ classes can do. Including inheritance and virtual methods, when you really really need them.
Only much more cumbersomely.
C++ is superficially similar to c in a lot of ways that don't actually translate well across the boundary between the two.
So some c things get misattributed to c++ and many c++ things get misattributed to c and disentangling these is nearly impossible if you aren't intimately familiar with both of them.
Being intimately familiar with either is a detriment to maintaining unmuddled working knowledge of the other.
Maybe it's just me, but I can no longer live without those.
Any competent butcher will never cut themselves.
C++ on the otherhand is way simple to use and really straightforward.
I like Zig too.
The simplicity is either in the language and tooling around the language, or it is in the code you read and write in that language. C chose to be simple in the language itself and not in the code.
The single greatest praise that I will give to C is that the entirety of the language can be held in the mind of the programmer using it, with zero need for reference. This is impossible in most other languages.
Spot on.
> C chose to be simple in the language itself and not in the code.
But it market itself being simple so people even newcomers think that C is simple in every regard. Only few people rarely acknowledge this fact.
> The single greatest praise that I will give to C is that the entirety of the language can be held in the mind of the programmer using it, with zero need for reference. This is impossible in most other languages.
In other languages, which parts you are unable to held in your mind?
The only instance where I need references in C++ is STD library features. But if we measure, it take less time than if we were to reinvent it on C.
I'm not saying C is the right choice for every project. C++ isn't either. C++ might be a pretty good language for doing the sorts of mid-level things that the people on the C++ language committee like to do (surprise surprise) but there are many broad domains at both higher and lower semantic levels for which it can be a poor fit. For a lot of low-level stuff a language that lets people define their own domain-specific abstractions will beat an "every bell and whistle and all wrong for what we're doing" language every time.
It gains you approximately nothing, as far as I can tell.
C++ STD lib is not a big mess. At least, I am using it for decades. I don't know if you really used it because those who are against STD doesn't understand the point of abstractions and it's utility. They always tend to cite why would I use vector when I can create a "simple" linked list myself with pointers.