304 points · by signa11 · 7y ago · 187 comments
For things that don't need classes (and there is a lot of code) I stick to C. But if I need the OOP benifits then I go with D. As a bonus, the C programmers and JavaScript programmers that I work with can read the D code and get most of it on the first try.
If you haven't used D, spend 30 mins and write a four function calculator. Then take the remaining time adding some kind of internal function line sin, cos, etc. You'll be suprised at how fast you can pick it up.
Granted, the above is a toy exercise, it's not writing an enterprise solution. But it's a little more than the standard "Hello Sailor, new in town" program that people start off with.
The key is to realize C++ is not a language, but a federation of languages. You need to cherry pick a subset you what you want to use and stay disciplined. Otherwise, it is a mess.
Out of places that are vaguely keeping up with C++, the only thing I'd consider sub-setting that is commonly applied to C++, is disallowing exceptions and RTTI. There are at least decent reasons for this. Yes, there are places that have additional constraints (like "C with classes" style, i.e. no templates), but it's much more rare (and even more rarely technically justified).
Sub-setting should not be confused with the fact that in many cases, the language does not push you as hard down a specific path (for better or worse), yet it might be beneficial for a specific company in a specific domain to have a common solution for something, which results in the company style guide saying: "for this use case, use company_lib::foo, not XYZ".
Where I work we use pretty much all of C++, as appropriate, that is there is no blanket ban on anything, or official subset. That does not mean that e.g. there is virtual inheritance all over the codebase; that's a feature you should pretty much never need to use. Writing code appropriately and consistently can only ever be done via discussion and code review; no subset will ever magically fix these issues anyway.
Coming from C and thinking of everything in terms of pointers, it was already foreign enough, but the problem was that I couldn't find a definitive reference on how these features interacted and how to use them together successfully. So I gave up on C++. Maybe if I was motivated by needing it for a client project I might have gotten further, who knows.
The issue is that no matter how disciplined you are, others will be using a different subset of the features available and you end up using different "languages", even when everyone on your team is ostensibly writing "C++".
You can write generic imperative C++ by using lots of templates, OO code that looks like Java, low level imperative code similar to C, and even functional code.
I can personally say the same thing about Haskell or Common Lisp. Perhaps it's not that extreme, but there are many ways to solve problems in those languages. Even some funny jokes about Haskell exploit this:
https://www.cs.utexas.edu/~cannata/cs345/Class%20Notes/10%20...
I've noticed two strains in language design, which I internally call Scheme-style and Common Lisp-style:
Scheme-style languages are the trimmed-down languages, often built around a big idea which animates the rest of the design but not always; the defining concept of Scheme-style languages is always how much they can remove to get a pure design, a design which supports writing code in one style. Python, Smalltalk, C, and Scheme are all languages in this mold. Java is kind of a compromised Scheme-style language, or two of them (C and Smalltalk) rammed into each other at high speed, which also goes for Objective-C.
Common Lisp-style languages have mini-languages inside of them, or at least support multi-paradigm programming as a core design goal; you can trim a Common Lisp-style language into a Scheme-style subset, but you can't extend a Scheme-style language into something more Common Lisp-like unless you really are dealing with Scheme and have (hygienic) macros to use to add more syntax. C++, Perl, and Common Lisp are all Common Lisp-style; Unix shell is Common Lisp-style in practice because it encourages programmers to write in a bunch of relatively Scheme-style languages at once, all in the same program.
Note that both Scheme and Common Lisp have a conceptual core in the Lambda Calculus and axiom-like special forms. C++ lacks this and Perl doesn't really have it either, but most people don't write huge codebases in Perl.
https://github.com/fiddlerwoaroof/objc-lisp-bridge#type-dire...
(for a whole program look at: https://github.com/fiddlerwoaroof/objc-lisp-bridge/blob/mast... )
Not much to add to the conversation here, but for some reason every time I read this it gets funnier and funnier.
But I do like your breakdown, it’s what I’ve been thinking whenever I see discussions like this.
.. and then ensure that all suppliers of source code into your project stick to that subset.
That and metaprogramming in D is all compile time so you get RSI-free hands, for free.
I'm sorry, but even though I think D is a great language, there are plenty of usecases where D isn't a viable alternative to neither C or C++.
If D had all those missing features, or if you compared D to some other mainly-GC:ed, statically typed and compiled language, I think the syntax comparison would have been more fair.
Visual appearance is a rather weak reason for preferring one language over another (especially if it's for explicitly personal reasons).
This is one of the things i dislike most about templates in C++. Even today reading template code with its nested syntax takes me time to unpack and understand. Symbols do affect comprehension and i would be quite interested in knowing whether somebody has done a study w.r.t. the various programming languages.
I'd use D anyway just for the GC or whatever, less compiler fighting, betterC etc. Procedural, OOP, functional, yay.
A lot of the standard library ranges are inherently lazy and therefore require no interaction with the GC. Exceptions are also nogc now.
If you never allocate from it (which is able to be verified very easily with the @nogc attribute), it will never trigger. You can disable it and trigger when you feel it is needed. You can choose to just leak.
The default GC is OK, but not great. However it recently was made multithreaded in the mark phase so it is much faster than it used to be. There is a fork based (on linux only IIRC) GC, used by several companies for hard realtime systems, that marks and sweeps in a separate process with CoW pages.
D has a built-in GC by default and doesn't force you to manage memory like Rust. Also, the author mentioned that D is pretty straightforward to anyone with some basic programming knowledge (think C, C++, Java, and C# which fits the majority of coders). Rust is very different from those languages. My main goto language is Python and I can understand D a lot more than Rust which confuses me to no end (disclaimer: I'm a total noob).
Go is probably as easy to read as D if not more and is also GC and fast. It is also very spartan. I bet D has a lot of additional features.
Go is okay but you can't get clever with it. You're productive from the start butit becomes routine quite fast and at a certain point there isn't anything new to learn. Error checking is also quite annoying.
D has the best of both worlds and it also plays nicely with C/C++, something that the author of Zig also understood is a must have in any language that aims to be a better C/C++. In D one is productive from the start and there's always something new to learn. And one learns it as they code, without having to first read Programming in D by Ali Çehreli to make any sense of the language.
I also tried Crystal and liked it but one is more productive in D and Go without any prior knowledge of those languages. I was kind of annoyed by the fact that Crystal removed the for loop, which works perfectly fine in Ruby.
http://jordi.inversethought.com/blog/advent-of-d/
The richness and flexibility of compile-time features almost make it feel like a lisp, with the slight downgrade of sometimes working on strings of source code instead of sexps. Regardless, like the article says, D's metaprogramming alone is worth the entry price of reading a few books or tutorials about the language.
There are a LOT of things C is blamed for, and languages try to introduce complicated syntaxes and abstraction to prevent them from happening, however, most of these other languages are ALSO open to the same security issues (or sometime, more), just on a different level. Perhaps they look a lot safer because they haven't had the same level of scrutiny as good old C. In the meantime they introduce a 'duh/WTF' effect when you try to bring someone else in on the codebase.
C with good static analyser coverage (cppcheck, clang 'scan-build', smatch[0]) and reasonable discipline is pretty easy to maintain, VERY easy to debug, extraordinarily low footprint and very fast, so taking the time and having a BIT of discipline to harness that power is well worth it.
As the article mentions, I'm one of the guys who did 20 years of C++ before 'reverting back' to C, and I'd LOVE a few of the things I've had to give up -- however, a new language is not really something I need.
Consider C's Biggest Mistake:
https://www.digitalmars.com/articles/b44.html
You can use D in -betterC mode, write code pretty much just like you would in C, and not have that problem.
I do not think it is a significant problem in C. It might be more of a problem in C++.
> You can use D in -betterC mode, write code pretty much just like you would in C, and not have that problem.
D is an improved, more polished version of _C++_, not C; "-betterC" mode is misleading, it is more of a "betterC++" mode (features: classes, exceptions, RAII, templates).
"The simplicity of C is more useful than the additional features of C++." -- (Sam Watkins) s/C++/D/g
Don't get me wrong: D would be a great replacement for _C++_, but not C. For a better C I would look at a subset of Go (GC would have to go away).
(It does have RAII without using exceptions.)
How often do programs in non-C/C++ languages get remote code execution vulnerabilities? I'm sure the CVE numbers will overwhelmingly show that most RCE-capable vulnerabilities are in C/C++.
Sure, it occasionally happens in other languages, but practically only when someone does something like misuse one of a specific set of APIs that allow code loading. In C/C++, any code that slightly fucks up writing to an array or passes a pointer to previously-freed memory around can cause a RCE vulnerability that lets an attacker literally run code on your system and take it over. Inspecting a C/C++ codebase made by a junior person for vulnerabilities is a total nightmare. Inspecting a codebase in any other language for RCE vulnerabilities generally means you grep for a couple APIs and look at how they get used.
This is where it is critical to differenciate C and C++.
https://jaxenter.com/security-vulnerabilities-languages-1570...
> Total reported open source vulnerabilities per language:
> C (46.9%)
> PHP (16.7%)
> Java (11.4%)
> JavaScript (10.2%)
> Python (5.45%)
> C++ (5.23%)
> Ruby (4.25%)
So Sure, RIGHT NOW the runtime might be safe from scrutiny, but is it because its SAFE or just not as such a high profile, just yet?
On the other hand I DO agree that 'junior' programming will always be a problem, regardless of the matter, and pretty much, regardless of the language.
The runtime (whichever one that is) is safe because its behavior is defined by design for all inputs. Yes there could be a bug, but the design is that all inputs should be defined, and doing something for any given input isn't rocket science. Out of bounds array indexes either panic/throw or return empty lists. That can lead to crashes and logic errors, sure, or maybe DOS attacks, but it cannot lead to undefined behavior or remote code execution. That's a world of difference.
C and C++ by design expose heaps of undefined behavior to the caller. The tools for detecting UB are imperfect and don't work if the relevant inputs never show up in test cases. Even when veteran C coders develop the techniques and habits that let them write correct C, mistakes tend to show up at the integration points between libraries written by different people with different techniques and habits (https://youtu.be/HgtRAbE1nBM?t=2344).
Actually, the situation for C is even worse than that makes it appear. C, both the language itself and the infrastructure ecosystem around it, actively fight you when you try to build and use tools to proactively find problems. The only tooling that tends to be effective in practice is built on dynamic analysis, which means that you can only be in confident in the safety of your code as you can be in your testing regime--and there are very few, if any, codebases that have a strong enough testing regime.
We, as an industry, have almost 50 years of coding in C. And that experience has told us that the effort it takes to build safe C code is beyond the discipline of most, if not all, development teams.
How often are there bugs in language runtimes that cause vulnerabilities in programs that are exploitable by users putting in different data into an otherwise secure program? (I'm not talking about the case where the runtime has a sandbox that breaks when the user loads bad code into it; this is a use-case C/C++ don't even try to address so that would be comparing different things. I'm talking about cases where someone is running a program that communicates over the network and the program's own code is written correctly, but a problem in the runtime makes it so the program is vulnerable to remote code execution.) The main example I can think of like that was Shellshock, which was horrible, but I would never have held up Bash as an example of a safe language. Bash has always been on my short list next to C and C++ of languages to avoid because of how easy and common it is to make mistakes that are practically unnoticeable in review.
>On the other hand I DO agree that 'junior' programming will always be a problem, regardless of the matter, and pretty much, regardless of the language.
Junior developers can write a buggy mess in any language. C/C++ are practically the only popular languages where a junior developer can accidentally write a backdoor in average-looking code that doesn't use any APIs.
I can tolerate some bugs in my software sometimes, but exploitable bugs are an entirely different thing to me.
EDIT: I thought about it a bit more and realized it cuts both ways. If you have an RCE in a standard library a lot of programs get an RCE for free while it's not patched. So yeah, a bit of a mixed bag.
Maybe that's because most software is written in C/C++?
The arguments that C/C++ are just as safe as other languages and that's it's just a matter of opinion or experience are unfounded. It's like saying a minefield is just as safe as anywhere else to walk because you can randomly suddenly die anywhere else too because of stuff like strokes or heart attacks. You just gotta have good landmine senses and it's your own fault if you can't avoid them.
a) C allows you to program "everything"; from big honking servers (backend and frontend), networking protocols and systems etc. and all the way down to itty-bitty 8-bit MCUs. Basically from above assembly to any sort of application you might care about.
b) C is the de-facto "glue" language to everything i.e. the "assembly" of high-level languages. Almost all languages allow you to link to a C module.
I am often mystified when people say C is "hard" when they program in languages like Java/Python/Javascript etc. To me these languages are baroque and hard since they require more mental effort to memorize and use the bazillion frameworks, libraries, objects and methods. I find them all quite overwhelming.
Here are some examples of why people say C is hard:
https://pzemtsov.github.io/2016/11/06/bug-story-alignment-on...
no, almost all languages allow you to call into your operating system's native dynamic library format.
That this binary was originally built with C, C++ in extern "C", fortran, ADA, D -betterC, Pascal... does not matter at all.
C just happens to be the most popular language for building those...
Not quite; the point of using the phrase "link to a C module" was to point out that all of them conform to the applicable "C ABI" for a platform and therein lies C's strength as a "glue" language.
The GCC team thinks differently, since GCC moved to C++ [1]
If you mean real hardware access, not even C can do that unless it is running bare metal without an underlying OS or MMU controlling the access, both situation outside of ISO C specification.
The betterC scenario has intrigued me before though, it seemed like a win all around since you'd be using C libraries anyway. I'd love to hear others experiences and anecdotes with this.
You have relatively clean access to all C libraries. But I do not know if that is relevant enough in your area of work/play.
And the standard library is also pretty nice. Sure, it's nowhere near Python's Batteries-Included package, but it can get you quite far.
I'm yet to put zig through it's paces but you can include header files directly, theoretically that makes it a much better drop in replacement.
I thought much of the point of D as a programming language would be its "relatively clean" access to external C++ libraries, which is not a feature many other languages share? (whereas it is of course quite common to have a foreign-function interface with C.)
They're working on it, but there's a lot more work to do: https://dlang.org/spec/cpp_interface.html There's a reason other languages don't have easy C++ interoperability.
> it is of course quite common to have a foreign-function interface with C
Yes, but it's not trivial for the most part to interface with C code. D is designed to make it easy - to the point that you can #include a C header file and you're good to go.
> As I said, it’s a superficial example, but I think it shows a general difference in philosophy between C++ and D. (If I wanted to make the difference even clearer, I’d use an example that needed iomanip in C++.)
iostreams are not in C++ because C++'s philosophy is actually that iostreams are great. Everyone knows they suck. They are there because without variadics, there isn't a good way to do type safe text output in the style of printf. And I mean, not even runtime type safe. Chaining of some kind is the obvious way to simulate variadics when you don't have variadics. And at the time, they thought it was better to get something type safe into the standard library, then gate it behind variadics which could (did) take a long time. Voila, iostreams.
C++ is quite literally in the process of standardizing a library that will bring type safe printf (a la D) to C++. The same way that 8 years ago, C++ finally managed to standardize variadics after quite a lot of effort.
The disadvantage of being an old language is that it can be hard to stay caught up with features. The advantage is that you get a huge base of existing developers, knowledge, libraries, etc.
Bloggers love to make things about big picture philosophy because it makes for better blurbs but many things in reality are just engineering decisions. D had the luxury of creating metaprogramming syntax from scratch after one if its creators was one of the main people to discover the power of "accidental" TMP in C++. C++ is still trying to bend accidental TMP into something more bearable to use without breaking everything. The differences here are more practical than philosophical.
I think an equally important point is that IO streams in C++ are extensible. You can make your own user defined types work with them. There's no way to add "printf() support" to your own type in C.
Not sure how portable it is but you can define conversions for your own types: http://www.gnu.org/software/libc/manual/html_node/Customizin... . The format and format_arg attributes give you compile time support: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attribute... .
AFAIK it's that code which compiles in both c and d should have the same behaviour; not that c code should necessarily compile in d. Examples of c that don't work in d are trivial.
> there are tools to convert C to D (As used in the dmd compiler backend (which dates back to the 80s I believe, but is now in a tasty form of spaghetti D)
Dmd's backend was ported by hand. What tools are those? I know there are tools to convert header files, but I don't know of any that actually convert code.
Not quite, the c++ source was massaged to be free of weird corner cases of the grammar and preprocessor (e.g. enforcing no spaces between '#' and the preprocessor keyword) and then a tool called magicport was used to convert the frontend in one shot. The backend was mostly converted by "hand" (i.e. grep after some more massaging).
There are several tools to translate headers though dstep[1] and dpp[2] come to mind
[1]: https://github.com/jacob-carlborg/dstep [2]: https://github.com/atilaneves/dpp
> Dmd's backend was ported by hand
I stand corrected then. Visual D has one cpp2d built in, which I assumed was used
You'd be right!
> but is now in a tasty form of spaghetti D)
Haha. It's still as awful as the C code it was manually converted to D from. I've been slowly improving it bit by bit.
Could a step forward be to start afresh and then call into the old backend stages but ultimately rewrite them in more bearable code where possible? Might be a compile time trade-off there, to an extent.
I agree that the Digital Mars implementation looks like the sanest.
C and C++ can compile to anything - thats a major use case for me
WASMV is completely doable but there's no C environment( at all) so you have to do it all yourself
It also depends on what your programing if you looking at system level stuff currently the two languages I would look at are C and Rust. Heck even for some system stuff your still required to use assembly.
Anything else choices are more flexible and productivity might matter more.
Honestly, despite C's flaws very few languages occupy it's niche and flexibility. Like you have to be doing something right to some degree to last almost 50 years. I would say a lot this comes down to C's simplicity yet still having a lot of power as a language.
a) you absolutely need performance, so a GC is out of question b) you don't need absolute performance
In case a) I don't think there are better solutions than C In case b) you wouldn't use C, to begin with. C#, Go, Java are ok.
in particular, and i've read that writing kernels isn't feasible in Go. it appears not to be an issue of performance. something about the runtime prevents writing kernels altogether.
like the linked article says
https://drewdevault.com/2019/03/25/Rust-is-not-a-good-C-repl...
rust has a lot of features (generics, etc.) aside and apart from the memory management strategy.
i'm also unaware of a procedural language that has the feature stability of C or Go as well as the ability to write kernels or embedded code with the memory safety of rust.
currently wondering how easy it'd be to tack rust's memory model onto another language, alef in particular.
C is only relevant as long as we will have UNIX and POSIX around.
First time I used D was before the version 2, back when there was the Tango library. D seems to have improved quite a bit since then, but it's still in the same position as before.
Really not the same thing. Compile time asserts allow you to check any compile time value. For instance say you were writing OpenGL code and your struct needs to have a size that is a multiple of 16 bytes. In D that's easy:
static assert(sizeof(Data) % 16 == 0);#define ASSERT_BUILD(x) \ do { char array[(x) ? 1 : -1]; (void)array; } while(0)
static char foo[10]; ASSERT_BUILD(sizeof(foo) >= 10);
char * i = malloc(1);
ASSERT_BUILD(i);
That just silently compiles and runs without triggering any failure. Whats worse is you can never be sure whether your assert is passing or the compiler decided not to run it.A common strategy is to use a self-describing variable name like `static_assertion_failed`.
The use of scope(exit) is actually very useful because, for example( short of using RAII) how many times do we all forget to free or close a file. Programmers make mistakes, but if you give them the tools to not fuck up as idiomatic parts of the language: They will use them.
That's not strictly true. For example, complex object assignment _might_ be turned into a function call by the compiler.