Was Linus Torvalds Right About C++ Being So Wrong?
Nerval's Lobster writes: Perhaps the most famous rant against C++ came from none other than Linus Torvalds in 2007. "C++ is a horrible language," he wrote, for starters. "It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it." He's not alone: A lot of developers dislike how much C++ can do "behind the scenes" with STL and Boost, leading to potential instability and inefficiency. And yet there's still demand for C++ out there. Over at Dice, Jeff Cogswell argues that C++ doesn't deserve the hatred. "I've witnessed a lot of 'over-engineering' in my life, wherein people would write reusable classes with several layers of inheritance, even though the reusable class wasn't actually used more than once," he wrote. "But I would argue that's the exception, not the norm; when done right, generic programming and other high-level aspects of C++ can provide enormous benefits." Was Linus going overboard?
The problem with C++ is that it's way too easy to write write-only code, because the language has so many features that nobody but language experts understand all of them. So we all program in different dialects, and then scratch our heads when we read other peoples' code.
I always get halfway through a Nerval's Lobster summary before my anger/indignation/smug validation gives way to the sad realization that Dice has trolled me yet again.
Could we stop having Dice articles submitted by Nerval's Lobster? Why not fully disclose that the story was submitted by the corporate parent of Slashdot?
Oh no, on the contrary. There are plenty of idiots who can write code in C++.
/ Grabs popcorn
// Dons asbestos armor
Linus was not going overboard. In this rare instance, I'd argue he hasn't gone far enough.
A better specified language, with fewer holes in its design, wouldn't have these problems between 'language' and 'compiler'.
The ability to fuck it up is a good thing, because there's a spectrum, and you can also knock it out of the park.
What comes next, a thread on "is Emacs better than Vi"?
My first program:
Hell Segmentation fault
Although the language itself isn't truly, truly bad, the only thing that made it tolerable was a library like Qt. STL and Boost are so shocking it isn't even funny, as well as the attitude amongst many that they are some kind of 'standard'. That's where C++ really did go off the rails.
Need the ability to moderate an entire Article/Summary as Clickbait or Troll.
I have read maybe 1 billion articles about language X being better than language Y and in many cases it is pure religious fanaticism; someone has committed to a language and now justifies that commitment with zealotry. A very common refrain about any given language is how many people write poor code in that language. This argument is often reserved to support the more "sophisticated" languages. For instance it is pretty much a gold medal sport to crap on PHP; and yes there is lots of terrible PHP which probably stems from the fact that it is often someone's first language and that someone is self teaching.
Then other languages are looked at as toy languages by those who resent them, Python would often be a victim here.
Then there are the wonderful charts of speed which in theory would justify everyone using ASM optimized to their CPU.
But for me it is not one language but a pairing that has caught my heart. Python and C++ do just about everything I want. Python is just so damn productive. Then I use C++ for where Python falls down on speed or the environment itself is not conducive to C++ (embedded and multi-platform Mobile).
But to answer his cry about people over-engineering things with silly STL uber inheritance type crap. That is where oddly enough the zealots of C++ are their own worst enemies. They love C++ so much they are giving it a bad name. Many people use STL in some purist way that completely blows Keep It Simple Stupid out of the water.
But I really do hold a special revulsion for anyone who claims that their language "Enterprise" which translates to me as so shitty that nobody will notice that most of your drone developers are also shitty.
If you care about performance, the ability of C++ to "run on the iron" is a valuable tool to have in your arsenal. Add in inline assembler, and IF YOU KNOW WHAT YOU'RE DOING you can write blazing fast code in C++ and still provide a sensible code architecture.
There's no sense in blaming the language for the abuses developers have written -- you might as well indict English for the horrible spelling and grammar of many Americans...
If you know what you're doing, C++ is a terrific, powerful language suitable for a plethora of projects. On the other hand, if you don't know what you're doing, well, I guess there's Visual Basic or C#.
A better developer who understands what it is he or she is trying to accomplish would help more.
I'd say I've seen just as much piss poor code written in Java and C#, but that'd be a lie. I've seen FAR worse code written in Java and C# than I have in C++ because the level of entry is much lower.
When I was in college, not understanding pointers means you didn't graduate. Now... I interview "C# Developers" who claim 10+ years experience who can't tell me the difference between pass-by-value and pass-by-reference, and don't know the difference between the heap and the stack.
In 1998 David Gelernter wrote a book that effectively argues that elegance and beauty in engineering are essential features that lead to benefits beyond the merely aesthetic.
He is still right.
The 'elegant' and 'concrete' example in TFA is ugly and hard to follow, even with plenty of understanding of lambda expressions and languages that offer them. I have other, better high level language options and other, better low level language options. C++ fails the test. C++ is not for me.
I should use this sig to advertise my book ISBN-13 : 978-1501515132.
Bad programmers can produce bad code in any language, including one as well/thoroughly specified as Ada. The difference, though, is that what that code actually does is less subject to interpretation by the compiler.
I've observed that two Ada programmers will argue, "Is this program legal?" If the program is legal, they both -know- what the compiler will do (modulo the rare compiler/optimizer bug, which was usually caught through the stringent compiler validation.)
Two C++ programmers will argue, 'What will my compiler do with this code?"
Two C++ programmers will argue, 'What will my compiler do with this code?"
You have a very good point, but that's less about the language and more about the compiler. Arguably the most broken compiler was (and likely still is) Microsoft's Visual C++.
But somehow C# is "fixed". LOL.
Linus was right (I didn't agree with him when he wrote that but I do now). Jeff doesn't answer any of the major issues with c++: Lack of standard ABI (preventing interop with other languages), insanely complex grammar, years of paradigm shift, action at a difference, lack of abstraction away from computers, etc. Java/C# have completely displaced it in the business world and C still dominates system programming. C++ would be already obsolete except that it caught a big with the gaming industry...real-time games can't tolerate GC languages and C is considered too baroque to many developers.
Linus is doing systems level work. At systems level work, there are a lot of mediocre and bad programmers who use the common language of C++. Those who know c well are unlikely to be the mediocre and bad programmers.
That is really a truism across all fields and languages.
In the business world with business logic, there are a lot of mediocre and bad programmers who use the common language of Java. You can filter out many of them by adding a skill requirement of some other less-used languages inside that realm of business software development.
In a field where everyone is doing Ruby development and you don't want mediocre/bad Ruby programmers? Require them to also demonstrate proficiency in another language.
In a field where everyone is using C#? Require them to also demonstrate proficiency in C++ or some other language.
If you only require a single thing you can get unskilled individuals with only a single skill. If you require multiple skills you are more likely to get more talented individuals, since the talented, higher producers tend to pick up a wide range of skills.
//TODO: Think of witty sig statement
I just looked through Nerval's Lobster's last 15 contributions. All were article submissions, Nerval's Lobster doesn't appear to comment on anything. Here's the list:
Every single one of them is from dice, though only a few of them actually make that explicit (the non-explicit ones are marked [Dice*]. A large fraction of them are related to human resources and hiring people, which I've marked [Hiring]. So its like Nerval's Lobster is using Slashdot as advertising and recruitment channel for Dice.
The average quality of these submissions was very low in my opinion - lots of vacuous pointy-haired-boss buzzword stuff. Very un-nerdy. How did these get through submission moderation? Were they even subjected to it?
C++ was the first popular fast OO language. As such, there's a lot of confusing cruft left behind. Consider overloading the && operator or || operators. You should never do this*. But someone will come along and do it anyway. You can't get rid of the feature because of backwards compatibility and yet it's miserable. We can go down the list from polymorphic arrays to calling virtual functions during constructors. All things one should never do, but the language keeps them there for the sake of backwards compatibility.
Languages like Java fix some of these problems by explicitly not allowing operator overloading (which is heavy-handed) but enforces some readability.
As others have said, using good 3rd party libraries like Qt makes the language tolerable, but in the legacy applications I've supported, there's no shortage of programming faux pas made possible by the language (like assumptions about the order of static variable destructors -- which is compiler dependent). As a programmer, it can be fun and productive since simply using the better parts of the language can make programs easy to write and read. As a maintainer, it's a smorgasbord of bad programming practices which the language makes no attempt to prevent.
That said, Linus really likes the new version of Subsurface based on Qt. So there;)
* Scott Meyers More Effective C++ p.35
-- Political fascism requires a Fuhrer.
C itself has so many pitfalls. For the best tour review the underhanded C contest. "features" like automatic concatenation of consecutive character strings means that if you leave out a comma in a list, the adjacent array element entries are concatenated rather than throwing a syntax error. That list will now not match the declared array size (one short, so there's a null or random pointer in the last element) but the compiler allows initialization listed mismatched to the array sizes. Character strings have to be declared one longer than the initialization string length (room for the unstated \0) but are accepted by the compiler if they don't giving an unbounded string length.
it's mind boggling to realize that
int (*int)[20];
int *int[20];
are different things.
the number of different ways an array argument in a function can be written makes code hard to grasp: is it a pointer, an array, a reference? many work alike but then fail in different ways.
The most common of all pitfalls and hard to read codes are the in-line initializations that pop up in function arguments and what not. this leads to classic blunder of writing = when you mean ==.
Perhaps the most insane thing is that If you declare an external function with the wrong prototype then any mismatch in the argument count leaves or takes something off the stack. Holy cow..... I mean what the hell? Why would any language ever ever ever let you leave a orphan argument on the stack, or worse pop one off that was not yours? This is very useful for the underhanded C folks however.
While I know there's little love for fortran, it's worth noting that none of those things is even possible in Fortran, so its an existence proof that there's not any necessity for those to exist and that it doesn't limit the power of the language to remove them. It's very fair to say that no simple typo will ever compile in fortran (yes very complicated offsetting typos can compile).
Some drink at the fountain of knowledge. Others just gargle.
"It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it."
That seems like a strange statement coming from someone who is one of the best programmer's on the planet - and who works closely with some of the others.
I don't disagree that C++ provides a lot of rope for substandard programmers to hang themselves with (and I've seen that done by someone who created layer upon layer of useless classes), but I assume Linus Torvalds doesn't hang out with too many "substandard programmers." So what's he afraid of?
Although C++ may not be for everybody, and it's far from ideal, I think it's generally a pretty good solution for the problems it's trying to solve. And it's not just me: it's notable that it dominates its niche as the primary C-inspired, object-oriented, compiled language.
Life is tough, but it's tougher if you're stupid.
I haven't read Linux's rant against C++ for a while, but he is correct that C++ isn't a good choice for an OS kernel. The only major kernel written in C++ that I know of is Windows NT, and it uses only a subset of C++ language features. In particular, it disables exceptions, disables RTTI, removes new/delete, and it doesn't have the standard library. Microsoft wrote their C++ compiler with this in mind, and there is a compiler flag to disable kernel unfriendly features (documented here). For everyone else, it's easier to just say that the C++ subset for kernel development is C (minus the standard library).
For non kernel use, C++ is superior to C in the hands of an expert programmer, but mediocre programmers who don't understand the language tend to write absolutely horrible code. And you can't take an expert C or Java programmer and expect them to write expert C++ code with just a few weeks practice. C++ is one of those languages that you have to dedicate a lot of time to, but it can be worth it if you require highly optimized code, have low latency requirements, or have low space requirements (areas where higher level languages like Java don't do well).
The major problem with C++ is that it's popularity means there's more crap code written in it by bad programmers than any other language. But, to borrow from a quote, a bad programmer can write bad C++ in any language. I've had plenty of experience with bad programmers and bad code, and the problems rarely stemmed from the language used. They usually stem from the programmer not understanding the language or the environment and from an all-too-common mule-headed desire to design their part of the software the way they want it to work rather than in a way that fits with the rest of the software. Languages where this isn't a problem are typically new enough that there's only been one "right way" to do things taught. C++ is old enough that there's a variety of approaches built up over time, leading to the problem.
As for C++ being so popular, that's because well-written C++ can beat most other languages in performance. I've learned one thing over the decades: good engineering in software is a great priority as a developer, but from the business side it's irrelevant. Business cares that it gets the correct results and it runs fast enough. It could be the worst Rube-Goldbergesque contraption under the hood, but as long as it gave the right results and performed like a Formula 1 car they'd be ecstatic. C++ makes it easy to achieve that in the complex software common in commercial environments.
This is all true, but I'm not sure how it's any different to almost any other popular language.
Java and C# have also evolved a lot of new language features in recent years. For many types of software, the way the code looks will also be heavily influenced by which libraries and frameworks are used in that project's stack.
It's the same story for web development. We have different flavours of JavaScript (ES5 in most browsers today, but ES6 just around the corner and supporting a wider range of programming styles), Python (2 vs 3), and so on. And with these more dynamic languages, the style is often even more guided by a framework if you're using one.
Even if you're not using pervasive third party frameworks or libraries, any project of non-trivial size is going to adopt its own conventions and build its own abstractions to suit its particular needs, and then the rest of its code will again become its own dialect written in terms of those conventions and abstractions.
In fact, I can't think of any mainstream language except for C that doesn't suffer from the "dialect" problem to some extent. And that's because C is a 20th century language in a 21st century world, so lacking in expressive power that it can't support any of these modern, high-productivity development styles and abstraction tools. Its ubiquity, portability and simplicity are assets, but they are effectively its only redeeming features in 2015, and as time goes by it will be necessary for fewer and fewer projects to choose C for those reasons.
"There are only two kinds of languages: the ones people complain about and the ones nobody uses." -- Bjarne Stroustrup
"If you attack a tool based primarily on not liking the people who use it, you're still just a bigot, no matter how famous you are." -- Anonymous Slashdot poster
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Good excuse for being lazy. I guess C++ is only for the iron willed. C++ is like a russian prison, you'll know who the men are real quick.
I have discovered late in the game that Python + Fortran is almost magical. It's better than Python C++. when you are needing fast algorithms or code close the metal (SIMD or GPU) then fortran provides all the muscle that you need without all the baggage of c++. You offload complex class and memory allocation to the python.
The amazing thing I really like about the fortran is that it compiles so damn fast compared to C++ that it's easy to write a python program that generates optimized fortran and then compile it at run time rather than simply pre-compile a C++ library to include. The fortran is cleaner looking and its hard to make typos. The limits and ugly bits of fortran are pretty much not a concern since those chores can be offloaded to the python.
Some drink at the fountain of knowledge. Others just gargle.
Languages run the gambit from script kiddie interpreted languages that were designed for children to cut and paste examples from the internet to esoteric languages meant to be used only by doctoral students doing research. C++ is a nice middle ground that requires some expertise to use correctly, but offers immense power if you take the time to develop that expertise. I've written 3d accelerated GUIs with it, I've written mathematical algorithms with it, I've written real-time embedded applications with it. All to great success. Of all the languages I've encountered in my 14+ years as a software engineer, C++ by far covers the broadest spectrum of possible applications.
This must be prefaced by mentioning that I have little experience with C++ code, the industry that I am in (Safety Critical Avionics software) absolutely refuses to use the language. In fact, the only thing I can really comment on are the reasons given to me as to why it is not used in this industry.
Compiling repeatability
Part of Safety Critical Avionics is that the binary must be perfectly re-creatable. At any time if an issue comes up someone must be able to rebuild the configuration used for compiling (versions, software packages, patches, etc.) and get a perfect match to the released binary, bit-for-bit perfect. Somehow most C++ compilers and libraries are unable to achieve this, using the same exact machine (no patches or changes) and compiling at a different time gives a different result. This has been demonstrated on several different compilers, using nothing other than standard libraries.
Code-to-binary and structural coverage analysis
For DO-178B Level-A software (paraphrase: "If this software fails, people die.") there is an analysis performed matching every line of code to a block of assembly, verifying that the compiler didn't add anything in that will cause issues. This prevents using some optimization options in C as that makes things too unreadable. However that also excludes C++ STLs and Boost libraries, as once you get into those libraries the traceability breaks down into impossibility very quickly.
Internationalization
On the side our company works on non-safety-critical software projects as companies need our help and we are looking for work. One of those side jobs is taking an application written over several years for a research facility and making it ready to be sold internationally. The project uses C++ and is converting X11 and Motif to QT, at the same time updating it to go from hard-coded English to strings that can be translated to multiple languages. The amount of cursing I hear from those engineers dealing with the internationalization of C++ far outweighs everyone else in the company on all other projects, apparently the design of the C++ language made many decisions that make such efforts very difficult.
So, mostly hear-say but from trustworthy and knowledgeable people, which is why I rarely touch the language.
DEMETRIUS: Villain, what hast thou done?
AARON: Villain, I have done thy mother.
Shakespeare invents 'your mom'
Set aside for a moment about which programming language you like to use the most, and how much it upsets you that "People you Do Not Know also Do Not Like what You Like". Many of us are employed to work on projects we did not start. In most cases, you are not going to start a job and tell people 'Henceforth, all code shall now be implemented in the One True Language'.
Assuming that, which language is going to get you paid the most and make you most employable?
I am a game developer, and I have worked on consoles and currently on mobile games. I have used mostly C++. But I have had to work with pure C and C#. Being able to write good code in C++ is primarily responsible for me being employed.
END COMMUNICATION
I can't think of any mainstream language except for C that doesn't suffer from the "dialect" problem to some extent
What about GObject?
As you say, C is a very bare-bones language, so it's not uncommon to see the object-oriented wheel reinvented as a C library, incompatible with the other such reinventions.
Casting is telling the compiler to do what you want. It's like saying "Shut up! I know what I'm doing, this thing is a XY pointer, even if you can't figure it out yourself."
In every language (which supports casting) you can make an error while casting by claiming something that isn't correct. Surprise!
Compared to C, sure. C was conceived in a spirit of pragmatic minimalism that's easy to love. I remember learning C from the K&R book back around 1980. That book was so thin it was practically a pamphlet next to books that taught you other languages. Everything about C was so neat, and trim, and cogent -- even the book everyone learned it from. That plus The Unix Programming Environment and perhaps Software Tools and you were cooking with gas.
It's natural to compare C++ to C; the very name encourages you to do so. It was to conceived to dovetail and build upon C. But it was conceived with an almost diametrically opposite kind of philosophy. C chucked out all the precious features that designers were putting into languages in the late 60s and early 70s and went with a tiny set of proven useful features. C++ implemented every bell and whistle anyone had ever dreamed up for object oriented programming, which was largely an academic topic that was full of clever but impractical notions. Well, it turned out that a lot of those things like operator overloading and multiple inheritance weren't all that useful in the judgment of later language designers, but you can hardly blame Bjarne Stroustrup from knowing that in advance.
It's practically impossible to overstate the practical success of C++. It took what was for most practicioners a theoretical idea (object oriented programming) and made it the way everyone programs by default. But you can't expect someone who loves C to love C++, which has almost none of the virtues that people admire in C.
Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
C++ is indeed a horrible language, and it attracts people who develop great pride in their memorization of needless complexity.
-jcr
The only title of honor that a tyrant can grant is "Enemy of the State."
You can argue about whether C++ is a horrible language (I lean toward "yes") in itself, but the libraries are what really push it over the edge. STL is hands down the worst collections framework I've ever encountered. Consider just a few examples of how you do some common operations with it, compared to doing the same things in Java and Python.
1. Check whether a string s ends with a suffix t.
Java: s.endsWith(t)
Python: s.endswith(t)
C++: s.rfind(t) == s.size()-t.size()
2. Check whether a collection c contains an element e.
Java: c.contains(e)
Python: e in c
C++: c.find(e) != c.end()
3. Split a string s into tokens based on whitespace.
Java: s.split() ... do you really want to know? Ok, check out http://stackoverflow.com/quest.... There you will find dozens of proposed solutions (many of them quite indecipherable), along with lots of debate about which one is best. The top voted solution has a comment on it (with several hundred votes) saying that it's a bad solution and you shouldn't use it.
Python: s.split()
C++:
Doing even really basic, common operations with STL requires way too much work and produces absurd, hard to read code.
"I'm too busy to research this and form an educated opinion, but I do have time to tell everyone my uninformed opinion."
The only major kernel written in C++ that I know of is Windows NT,
Apple uses a subset of C++ known as "kernel C++" for drivers in OS X and iOS. Back in the NeXTSTEP days we used Kernel Obj-C, and it's very sorely missed.
-jcr
The only title of honor that a tyrant can grant is "Enemy of the State."
Honestly, I find a random program written in C to be on average FAR less maintainable than one written in C++, usually because they end up reinventing the wheel about 50 times, usually poorly. The C program that I work on at work is one gigantic mass of poor wheel reinvention over and over again. Its impersonation of objects and inheritance (for sending message) is terrible, utterly terrible, it's almost impossible to build and send a message without messing up in some way due to all of the interconnected pointers. The macros they use to try to "simplify" it only make it worse. Some parts of the code have macros nested literally dozens of levels deep.
"Are you hungry? I haven't eaten since later this afternoon." -- Primer
There aren't, because C++11 is, well, a standard for 4 years only, and C++98 implementations were spotty well into the middle of the following decade. Finally, not that many people are writing kernels from scratch...
A successful API design takes a mixture of software design and pedagogy.
You're all talking about C++ and not LINUS TORVALDS! Have you all LOST your MINDS!? ;-)
Hey! He didn't even pick up a chair!
It's not a rant 'till someone has to place a furniture order with Staple's...
You have the right to remain sentient. If you give up the right to remain sentient, you will be elected to public office
google F2Py. You will find lots of tutorials. Most significantly you may notice that f2py is integral to scipy.
as for compiling fortran on the fly, this can be done through scipy as well or you can use system calls. Exactly how you do it depends on what compiler your system used.
Some drink at the fountain of knowledge. Others just gargle.
Symbian, BlackBerry OS, Wii U System Software, OKL4.
I'm sure I left some out.
sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
Yep hence Vala, which transpiles to C-with-GObject.
You're all talking about C++ and not LINUS TORVALDS! Have you all LOST your MINDS!? ;-)
I guess C++ is more controversial :D
Vala is surely the most ironic language yet.
GObject: because we don't want to use a whole new programming language just to add objects to C.
Vala: because GObject is better approached using a whole new programming language.
There are two bad ways to code in C++: the C way and the Java way.
You're talking of inheritance, that's something you use in the Java way.
C++ is a language for experts, but so is C.
There shouldn't even *be* an option to forget something that screws you over like that.
Every major compiler warns about that and has done for years.
And there are also some good reasons for not wanting virtual destructors because they can introduce unacceptable performance penalties in high performance code.
Check out any of the libraries that do fixed-length linear algebra stuff. They use (internally) quite complex systems of derivations to allow the resulting classes to have all the features you expect.
The resulte is that something like Vec supports all the operations you expect from linear algebra, but has precisely the same overhead as double[3]. If you had to have virtual destructors then you'd have to write the code C-style to get good performance.
The result would be code that is ultimately much less clear and therefore much harder to debug.
SJW n. One who posts facts.
Linus is possibly right with one thing:
> It's made more horrible by the fact that a lot of substandard programmers use it
C is simple and lean. Doing complicated stuff which is not required is not easy and prevents system-level software messed up with unrequired abstraction layers and patterns, which you can ususally find in the typicall Java-Software. Because Java make it especially easy and popular to use abstractions and patterns by so called "Software Architects". Spring with Inversion-of-Control and Aspect-Orientiered-Programming (non-readable source-code!) and Hibernate make especially reading source-code a big pain (it not longer readable source, it's a lot of spaghetti XML and annotations with weird bugs).
> In other words, the only way to do good, efficient, and system-level and
> portable C++ ends up to limit yourself to all the things that are
> basically available in C.
C++ is a Multi-Paradigm, one of this paradigms is low-level/system-level programing with simple C-Like code.
The offers a how lot of new features which make programming on high-level easier, faster and safer like RIAA and Smart-Pointers, Templates and STL-Containers, modern I/O-Stream and Strings and finally OOP.
Personally I tend to say, that OOP is an important part of C++, but the biggest achivement so far are Templates* and the STL. They allow both creation of big software projects. If done right, this big software is not complex software.
* Java doesn't offer the convenience of Templates, basically because Generics are just Autoboxing for Safety but nothing more.
We need to acknowledge the fact Linux Torvalz (tee-hee) is being utterly illogical (odd for a 10x programmer) when he utters that a language is bad because there are so many bad programmers using it. There are bad programmers in any language. If there's a preponderance of bad programmers using C++, it's not because the language is bad, but because it has been so popular (and powerful) for so long.