515 points · by bwidlar · 2y ago · 347 comments
Calling big endian "commonly used by modern processor types" when s390x is really the only one left is a bit of a stretch ;D
(Comments about everyone's favorite niche/dead BE architecture in 3… 2… 1…)
I agree with another GP's comment that modern doesn't mean popular/widely used.
1. That both byte orders are equally prevalent in the wild, particularly in systems that are expected to run modern C code.
2. That both byte orders are equally likely to be found in "modern" (new or updated) processor design.
It's not entirely incorrect, but a better phrasing could be used to clarify that little-endian is the more modern and common storage order, but you still cannot ignore big-endian.
POWER is bi-endian. In recent versions, Linux on POWER is little-endian (big-endian Linux on POWER used to be popular, until all the distros switched some years back), while AIX and IBM i are big-endian.
AIX and IBM i are probably not quite as alive as IBM mainframes are, but AIX is still arguably more alive than Solaris or HP/UX are, to say nothing of the dozens of other commercial Unix systems that once existed. Likewise, IBM i is just hanging on, yet still much more alive than most competing legacy midrange platforms (e.g. HP MPE which has been officially desupported by the vendor, although you can still get third party support for it.)
¹ on the OpenWRT table of hardware
Any recommended hardware I should use for bare metal development messing around? Hopefully priced like a SBC like the raspberry pi.
Want to move from making basic programs like adding, messing with functions, etc and bring my MIPS assembly up to a real hardware environment.
https://www.godbolt.org/z/bWfhGx7xh
...without -march=native it's a mov and bswap (so not too bad either).
If I want to live on cutting edge I would rather use C++2x or Rust rather than C.
Am I missing something? What benefit this supposedly modern C offers?
For the cutting edge I would recommend Zig btw, much less language complexity than both modern C++ and Rust.
One good but less visible side effect of C23 is that it harmonizes more syntax with C++ (like ... = {} vs {0}) which makes it a bit less annoying for us C library maintainers to support the people how want to compile their C code with a C++ compiler.
The microcontroller toolchains are generally built on top of GCC, so they get the features for free. There are some proprietary C compilers that are chronically lagging behind, but they are not nearly as important as they used to be two decades ago.
also, unless you're targeting embedded or a very wide set of architectures, there's no reason why you couldn't start using C23 today
I cannot remember the last time I saw C99 used. C codebases generally use C11 or C17, and C++ code bases use C++20
Why would I rather step into the world of C++ just to deal with that?
You have to know what you're biting into, before you use that.
Also most companies making those platforms are not good at updating their toolchains. Expecting developers to compile their own toolchain, that is unsupported by platform vendor, is too much to ask.
Also GCC dropped support for certain architectures along the way, and even if you are willing to compile your own toolchain, it may not work for you.
You could, in theory, just use C++ and be done with it. But like any C++ project you'd need a pretty strict style guide or even a linter, but this time it would have to be extra restrictive lest you slide into full C++ territory. And maybe that's a major stumbling block for some people?
"_BitInt(N)" is also ugly, reminds me of "_Bool" which is thankfully "bool" now.
[1] guard, defer, auto, constexpr, nullptr (what is wrong with NULL?), etc. On top of that "constexpr" and "nullptr" just reeks of C++.
That said, Modern C is an incredible book, I have been using it for C99 (which I intend to continue sticking to).
One of the few advantages of ISO standardization is you can just read the associated papers to answer questions like this: https://wg21.link/p2312
The quick bullet points:
* Surprises when invoking a type-generic macro with a NULL argument.
* Conditional expressions such as (1 ? 0 : NULL) and (1 ? 1 : NULL) have different status depending how NULL is defined
* A NULL argument that is passed to a va_arg function that expects a pointer can have severe consequences. On many architectures nowadays int and void* have different size, and so if NULL is just 0, a wrongly sized argument is passed to the function.
In my opinion, complexity doesn't scale linearly like this. Sometimes, in fact often times, having more complex tools means a simpler process and end result.
It's like building a house. A hammer and screwdriver are very simple. A crane is extremely complex. But which simplifies building a house? A crane. If I wanted to build a house with only a hammer and screwdriver, I would have to devise incredibly complex processes to get it done.
You see the same type of thing in programming languages. Making a generic container in C++ is trivial. It's very, very hard in C. You can make it kind of generic. You can use void * and do a bunch of manual casting. But it's cumbersome, error prone, and the code is more complex. It's counter-intuitive - how can C, a simpler language, produce code that is more complex than C++?
Or look at std::sort vs qsort. The power of templates and functors makes the implementation much simpler - and faster! We don't have to pass around void * and dereference them at runtime, instead we can build in comparison into the definition of the function itself. No redirection, no passing on the stack, and we can even go so far as to inline the comparison function.
There's really lots of examples of this kind of stuff. Point being, language complexity does not imply implementation complexity.
The constraints of the tool are inherited in the program; if the constraints encourage better design, then the program will have a better design. You benefit from the language providing a path of least resistance that forces intentionality. That intentionality makes the code easier to reason about, and less likely to contain bugs.
You do pay for this by writing more boilerplate, and by occasionally having to do some dirty things with void pointers; but these will be the exception to the rule, and you'll focus on them more since they are so odd.
Also, I wouldn't be saying this if people didn't constantly try to recreate C++-isms in C. Which sometimes you need to do. So, then you have this strange amalgamation that kind of works but is super error prone and manual.
I also don't necessarily agree that C's constraints encourage better design. The design pushes far too much to runtime, which is poor design from a reasoning point of view. It's very difficult to reason about code when even simple data models require too much indirection. Also, the severely gimped type system means that you can do things you shouldn't be able to do. You can't properly encode type constraints into your types, so you then have to do more validation at runtime. This is also slightly improving, starting with _Bool years ago.
C++ definitely is a very flawed language with so, so many holes in its design. But the systems it has in place allows the programmer to more focus on the logic and design of their programs, and less on just trying to represent what they want to represent. And templates, as annoying as the errors are, prevent A LOT of runtime errors. Remember, every time you see a template that translates into pointers and runtime checks in C.
I also think that it wouldn't be bad for code to be more generic. It is somewhat unnecessary for a procedure to allow an argument of type A but not of type B if the types A and B share all the commonalities necessitated by the procedure. Of course procedures with equivalent source code generate different machine code for different types A or B, but not in a way that matters much.
I believe it is beneficial for the language to see code as the description of a procedure, and to permit this description to be reused as much as possible, for the widest variety of types possible. The lack of this ability I think might be the biggest criticism I have for C from a modern standpoint.
_BitInt(N) isn't typically used directly but typedef'ed to the width you need, e.g.
typedef _BitInt(2) u2;
The 'ugly' _B syntax is needed because the combination of underscore followed by a capital letter is reserved in the C standard to avoid collisions with existing code for every little thing added to the language (same reason why it was called _Bool).AFAIK defer didn't actually make it into C23?
I'm also more on the conservative side when it comes to adding features to the C standard, but IMHO each of the C23 additions makes sense.
Correct, defer didn't make it into C23.
It (in its __attribute__((cleanup())) form) is also one of the most useful extensions in GCC/clang — but, again, for use in macros.
Both have compatibly implemented the standard C++ auto. Since 2011 or so.
Here's an example where Clang and GCC don't agree about the behaviour of auto in C23:
https://www.godbolt.org/z/WchMK18vx
IIRC Clang implements 'C++ semantics' for C23 auto, while GCC doesn't.
Last time I brought that up it turned out that both behaviours are 'standard compliant', because the C23 standard explicitly allows such differing behaviour (it basically standardized the status quo even if different compilers disagreed about auto semantics in C).
PS: at least Clang has a warning now in pedantic mode: https://www.godbolt.org/z/ovj5r4axn
The old definition did not even specify wether it was a pointer or an integer. So for platforms that did not follow the Posix ((void*)0) requirement it was a foot gun that had neither the type nor the size of a pointer.
> On top of that "constexpr" and "nullptr" just reeks of C++.
Probably because they where back ported from C++. You can still use NULL, since that was apparently redefined to be nullptr.
This code has a bug, and may even crash on some architectures:
execlp("echo", "echo", "Hello, world!", NULL);
This code doesn't have the bug: execlp("echo", "echo", "Hello, world!", nullptr);
Neither does this: execlp("echo", "echo", "Hello, world!", (char *)NULL);For starters, you have to #include a header to use it.
stddef.h on the other hand is required by most to get size_t
https://stackoverflow.com/questions/562303/the-definitive-c-...
I think 21st Century C by Ben Klemens and C Programming a Modern Approach by King are both more approachable alternatives as a modern C companions to K&R.
I like "Effective C" over "Modern C" because it's more engaging ... "Modern C" is super rigorous and feels a bit like reading an annotated spec of the language, which is what an expert may need, but makes for a dull read for a casual C user like me.
--
For your particular use case, have you considered C#? VS works much more nicely with it.
So, C23? ... that's nice and all, but, let's talk about it in 20 years or so T_T
I suspect that decades of C being effectively frozen have caused the userbase to self-select to people who like C exactly the way it is (was), and don't mind supporting ancient junk compilers.
Everyone who lost patience, or wanted a 21st century language, has left for C++/Rust/Zig or something else.
In my experience, Windows devs don't like being told to use a different toolchain. They may have projects tied to Visual Studio, dependencies that are MSVC-only or code written for quirks of MSVC's libc/CRT, or want unique MSVC build features.
I found it hard to convince people that C isn't just C (probably because C89 has been around forever, and many serious projects still target it). I look like an asshole when I demand them to switch to whole another toolchain, instead of me adding a few #ifdefs and macro hacks for some rare nice thing in C.
Honestly, paradoxically it's been easier to tell people to build Rust code instead (it has MSVC-compatible output with almost zero setup needed).
And back around 2010 MSVC still mattered a lot (which sounds weird from today's pov where most developers appear to have moved to Linux).
But OTH, few projects actually need C11 features (and C11 actually took one thing away from C99: VLAs - nothing of value was lost though).
C23 might be the first version since C99 that's actually worth upgrading to for many C code bases.
https://stackoverflow.com/questions/58815959/include-binary-...
#embed would be much nicer
D does not decay arrays, so D has array bounds checking.
Note that array overflow bugs are consistently the #1 problem with shipped C code, by a wide margin.
This isn’t strictly true, a C implementation is allowed to associate memory-range (or more generally, pointer provenance) metadata with a pointer.
The DeathStation 9000 features a conforming C implementation which is known to catch all array bounds violations. ;)
That actually really does exist already with CHERI CPUs, whose pointers are tagged with "capabilities," which catch buffer overruns at runtime.
https://tratt.net/laurie/blog/2023/two_stories_for_what_is_c...
https://msrc.microsoft.com/blog/2022/01/an_armful_of_cheris/
The what now?
Writing safe code is better than depending on safety features. Writing safe code is possible in any programming language, the only things required are good design principles and discipline (i.e. solid engineering).
In release fast mode, unsigned overflow/underflow is undefined in Zig whereas in C it wraps.
:-)
Of course C has many UBs that Zig doesn't have, so C is far less safe than Zig, especially since you can use ReleaseSafe in Zig..
char* thing; // good
char *thing; // bad
This ... is awesome. As a C++ "native" I've always found the "star on the right" thing to be really horribly confusing.
// mutable pointer to mutable data:
char * str;
// Immutable pointer to immutable data:
char const*const str;
// Mutable pointer to an immutable pointer to a mutable pointer to immutable data:
char const**const* strs;
I mean, one can reasonably argue that C & C++ declarator syntax is itself horribly confusing because it doesn't read left-to-right. But it is what it is, so why pretend that it's something else?
Takeaway #1: "C and C++ are different: don’t mix them, and don’t mix them up"
Where "mixing C/C++" is helpful:
- I "mix C in with my C++" projects because "sqlite3.c" and ffmpeg source code is written C. C++ was designed to interoperate with C code. C++ code can seamlessly add #include "sqlite3.h" unchanged.
- For my own code, I take advantage of "C++ being _mostly_ a superset of C" such as using old-style C printf in C++ instead of newer C++ cout.
Where the "C is a totally different language from C++" perspective is helpful:
- knowing that compilers can compile code in "C" or "C++" mode which has ramifications for name mangling which leads to "LINK unresolved symbol" errors.
- knowing that C99 C23 has many exceptions to "C++ is a superset of C" : https://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B...
The modern fmt-inspired std::print and std::println etc. are much nicer, preserving all the type checking but losing terrible ideas like stored format state, and localisation by default. The biggest problem is that today C++ doesn't have a way to implement this for your own types easily, Barry illustrates a comfortable way this could work in C++ 26 via reflection which on that issue closes the gap with Rust's #[derive(Debug)].
I’m not sure about the stdlib version, but with fmtlib you can easily implement formatters for your own types. https://fmt.dev/11.0/api/#formatting-user-defined-types
Hindsight is 20/20, remember that. Streams are not that bad of an idea and have been working fine for decades. You haven't named a problem with it other than the fact the operators are used for other stuff in other contexts. But operator overloading is a feature of C++ so most operators, even the comma operator, can be something other than what you expect.
>The biggest problem is that today C++ doesn't have a way to implement this for your own types easily, Barry illustrates a comfortable way this could work in C++ 26 via reflection which on that issue closes the gap with Rust's #[derive(Debug)].
You can trivially implement input and output for your own types with streams.
You appear to be a Rust guy whose motive is to throw shade on C++ for things that are utterly banal and subjective issues.
This disn't stop with <iostream>, they keep doing it - the latest example I can think of is std::ranges operations being "piped" with |.
#OUT + "Hello, " + name + "!";I think this is a very lazy and somewhat conspiratorial take.
C++'s IO stream library, along with C++'s adoption of std::string, is a response to and improvement over C's standard library support for IO. That alone makes it an invaluable improvement. It's easy and very lazy to look back 30 years ago and badmouth things done back then.
It's also easy to complain about no one proposing changes when literally anyone, including you, can propose changes. The only need to do the legwork and put their money where their mouth is. The funny part is that we see frameworks putting together their own IO infrastructure and it ends up being not good, such as Qt's take on IO.
But talk is cheap and badmouthing doesn't require a pull request.
The C library headers for libraries I write often include C11/C99 stuff that is invalid in C++.
Even when they are in C89, they are often incorrect to include without the include being in an `extern "C"`.
It takes a little bit of an effort to make a header work on C and C++. A lot less effort than making a single Python file work with Python 2 and 3.
Almost seamlessly. You have to do
extern “C” {
#include "sqlite3.h"
}
(https://isocpp.org/wiki/faq/mixing-c-and-cpp#include-c-hdrs-...)It's telling that every compiler toolchain that compiles C++ also compiles C (for some definition of "C"). With compiler flags, GCC extensions, and libraries that are kinda-sorta compatible with both languages, there's no being strict about it.
_My_ code might be strict about it, but what about tinyusb? Eventually you'll have to work with a library that chokes on `--pedantic`, because much (most?) code is not written to a strict C or C++ standard, but is "C/C++" and various extensions.
Absolutely true. I generally insist on folks learning C and C++ interoperability before diving in to all the "Modern C or C++" goodness. It helps them in understanding what actually is going on "under the hood" and makes them a better programmer/debugger.
See also the book Advanced C and C++ Compiling by Milan Stevanovic.
https://herbsutter.com/2012/05/03/reader-qa-what-about-vc-an...
> it is hard to say no to you, and I’m sorry to say it. But we have to choose a focus, and our focus is to implement (the standard) and innovate (with extensions like everyone but which we also contribute for potential standardization) in C++.
I mean, yeah if it came from a two member team at a startup, sure focus on C++, understandably. But Microsoft, what happened to "Developers! Developers! Developers!"?
This is how I managed to sneak C++ into an embedded C codebase. We even created some templates for data structures that supported static allocation at compile time.
Just like one doesn't use Typescript to keep writing plain old JavaScript, then why bother.
Sooo... yeah... I should definitely change company!
My god. That's amazing.
For example, the primary reason for the sentence seems to be from the text: "Many code examples in this book won't even compile on a c++ compiler, So we should not mix sources of both languages".
It's not at all about the ability to use c libraries in c++ projects or vice versa :S.... c'mon guys!
Why is that?
If you're asking why people use pre-increment by default instead of post-increment, it's mostly historical. The early C compilers on resource-constrained platforms such as early DOS were not good at optimization; on those, pre-increment would be reliably translated to a simple ADD or INC, whereas code for post-increment might generate an extra copy even if it wasn't actually used.
For C++ this was even worse with iterators, because now it depended on the compiler's ability to inline its implementation of postfix ++, and then prove that all the copies produced by that implementation have no side effects to optimize it to the same degree as prefix ++ could. Depending on the type of the underlying value, this may not even be possible in general.
The other reason is that all other unary operators in C are prefix rather than postfix, and mixing unary prefix with unary postfix in a single expression produces code that is easy to misunderstand. E.g. *p++ is *(p++), not (*p)++, even though the latter feels more natural, reading it left-to-right as usual. OTOH *++p vs ++*p is unambiguous.
Only on very rare occasions I need post increment semantics.
And in those cases I prefer to use a temporary to make the intent more clear
This is not one of those beginner -> journeyman -> expert cycles where coincidentally the way you wrote it as a beginner is identical to how an expert writes it but for a very different reason. I'd expect experts are very comfortable writing either { x = k; k += 1; } or { k += 1; x = k; } depending on which they meant and don't feel an itch to re-write these as { x = k++; } and { x = ++k; } respectively.
I'm slightly surprised none of the joke languages add equally frivolous operators. a%% to set a to the remainder after dividing a by 10, or b** to set b as two to the power b or some other silliness.
By the way, the US government did the profession no favors by including C++ as a memory-unsafe language. It is possible to write memory-safe C++, safe array dereferencing C++. But it’s not obvious how to do it. Herb Sutter is working on it with CppFront. The point stands that C++ can be memory-safe code. If you make a mistake, you might write some unsafe code in C++. But you can fix that mistake and learn to avoid it.
When you write C, you are in the bad luck shitter. You have no choice. You will write memory—unsafe code and hope you don’t fuck it up. You will hope that a refactor of your code doesn’t fuck it up.
Ah, C, so simple! You, only you, are responsible for handling memory safely. Don’t fuck it up, cadet. (Don’t leave it all to computers like a C++ developer would.)
Put C in the bin, where it belongs.
I see comments like yours everywhere all the time and I seriously think you have a very unhealthy emotional relationship with this topic. You should not have that much hate in your heart for a programming language that has served us very well for many decades and still continues to do so. Even if C was literally all bad (which imho isn't even possible), you shouldn't be that angry at it.
When I say put it in the bin, I don’t mean that good software hasn’t been written already with it, or can’t be written with it. But you should stop using it given the earliest opportunity. When given the ability to write object-oriented software, clever engineers with too much time add insane complexity justified by unproven hypotheticals. Believe me, I know very well why people shy away from C++ like a trauma response. Overly-engineered/overly-abstracted complexity, incomprehensible template syntax, inadequate standard library, indecipherable error messages, C++ has its warts. But it is possible to write memory-safe software in C++, and it is not in C (unless we are talking about little code toys!). My answer is that you don’t have to write complicated garbage in C++. Keep it simple like you are writing C. Add C++ features only to get safety. Add polymorphism only when it solves a problem. Never write an abstract class ahead of time. Never write a class ahead of time.
Downvote me all day long. Call me angry. When billions of dollars are lost because someone, in our modern age, decided to write new software in C, or continue to develop software in C instead of switching to a mixed C++/C codebase with an intent to phase out new development in C.
It’s hard not to get angry when modern software is written with avoidable CVEs in 2020’s. Use after free, buffer overflows, are you kidding me? These problems should have been relics in 2010+, but here we are.
1) https://gcc.gnu.org/projects/cxx-status.html#:~:text=C%2B%2B...
For instance, only sized types:u8...s64, f32, f64... no implicit casts except for void* and literals, no integer promotion, no switch, no enum, only one loop keyword (loop{}!), no anonymous code block, and no toxic attribute like "packed structure" which makes us lose sight of data alignment... no _generic, typeof, restrict, syntax based tls, etc...
But we would need explicit atomics, explicit memory barriers, explicit unaligned memory access.
Instead of adding and complexifying C to make writing a naive compiler more and more complex, long and a mouse and cat catchup "to the standard" tedious task, what should be done is exactly the other way around.
In end, I don't trust C officials anymore, I tend to stick to C99, or even assembly (I am currently writing rv64 assembly I run an x86_64).
> […] But we would need explicit atomics, explicit memory barriers, […]
You should read a change summary before complaining about bits missing from C99 that have in fact been added to C11.
> […] no toxic attribute like "packed structure" which makes us lose sight of data alignment […]
And you should also familiarize yourself with what's in actual ISO C vs. compiler extensions before complaining about bits that are in fact compiler extensions.
The pb is in ISO c11+ we got some of the missing stuff for modern hardware architecture, but also tons of tantrums (_generic, typeof, restrict....)
Is the usage of single linked lists still prevalent as the main container type?
Of course, it's still C.
> Is the usage of single linked lists still prevalent as the main container type?
As far as I can remember, the C standard library has never had any functions that used linked lists. Nor are there any container types, linked lists or otherwise, provided by C. So I'd say this is a question about how people teach and use C, not related to the language -- or language spec version -- itself.