r/askscience • • Oct 17 '12
Why are programs and operating systems still written in C+?
I guess it's more of a computer science question, but I've always wondered why some of the most advanced programs are written in a 25+ year old programming language. Surely someone has come up with a more efficient and powerful code, so why do people still use C+? Also, I don't know anything about programming and what not, so please use simple terms and phrases.
64
Upvotes
129
u/Tenome Oct 17 '12
First of all, it's C++, not C+.
For one thing, C++ is useful because it allows you to program both high-level and low-level code, meaning you can use it to write anything from video games to basic drivers. You can write programs that directly manipulate memory and are practically in "machine code", or you can use it to perform more advanced functions.
Furthermore, although the language is quite old, it continues to be updated constantly, with the most recent version, C++ 11, being released just last summer.
C++'s age is also somewhat advantageous, as there are thousands of existing libraries already written and available for use.
I'm sure there are other reasons but that's what comes to mind.
82
u/zelmerszoetrop Oct 17 '12 edited Oct 18 '12
EDIT:
I'm posting this edit up front so people will see it. As has been pointed out, I'm a mathematician, not a professional programmer, and some of the points you'll find below are not entirely accurate. For the most part, I stand by this post. However, there are two correction posts I'd like to mention. \u\binary_is_better points out in this response is that C++ does not generate massive amounts of machine code. Some of the corrections s/he mentions are things I intentionally glossed over (eg, interpreters vs. compilers), but many of the points made are valid and directly contradict me, particularly my final paragraph. Anybody who finds my post informative should read that post as well.
Furthermore, /u/lw9k points out in this post that there is very little, if any, efficiency loss going from assembly to C++. Another correction to my original post that you should read.
END EDIT.
First of all, while many programs are written in C++, many are written in more modern languages, like Perl, Python, Ruby, or R. But you're right, C++ is still very popular.
Programming languages can be classified in many ways, and one such way is by how directly they allow you to interact with the processor itself.
At the very basic level is machine code - the different strings of 0s and 1s that correspond to the instruction set of a processor. For example, my processor might use 00011001 might increment a certain register (ie, increase by 1 a certain value). Another processor might use 10011010 for the same task.
If you can't remember all the different strings of 0s and 1s, you can use assembly. You can write "INC A" in assembly, and the machine will know you really mean 10011010 or something. But watch out, because each kind of computer architecture comes with it's own assembly language, mostly, so your code might not be portable to another machine.
This was how early computers were programmed, but it was an enormous pain in the ass. Machine code and assembly language are incredibly difficult to read and to write (and to debug!)
With the invention of FORTRAN, COBOL, and other programming languages, code became decently readable. You could write your code in a program called a compiler, and the compiler would turn your abstract words like "IF" and "EQUIVALENCE" into the machine code. Commands used words like "GOTO" for control structure, variable definition became more intuitive - you could almost read it. A little later was BASIC, which was very understandable. I'll bet I could show somebody who'd never seen computer code before a really simple program written in BASIC, and they'd understand most of it. If you ever programmed on your TI-83 calculator in high school, you've used a variant of BASIC.
C, and the successor C++, were a step up. Again, programs called compilers would take your instructions and turn it into machine code that the computer could actually execute. But what's awesome about C and C++ is you can do both. You can interact directly with the processor, a lot like in assembly, but in slightly more intuitive ways. Or you can use abstract, high-level commands. You can (and almost always do) mix the two in any given program. C and C++ allow repetitive actions to be coded for in an intuitive way instead of using obtuse GOTO statements, they have an enormous number of available commands, and they support the addition of libraries to expand on those commands. These libraries play a huge part in the popularity of C++, which I'll explain in a bit. You could definitely understand some things in this language if I showed you - not everything, not without a little experience, but somethings. Look:
Without knowing any C++, you can probably decipher some of this snippet of code from a Solitaire game I wrote. I have a variable called "display_counter" - that probably counts along something that needs to be displayed, right? And while that number is less than 7, we're doing to do some stuff. What will we do? Well, while the display_location is less than the size of some stack, we'll display whatever's in that stack at the display_location. And then we'll increment the display_counter by one, and if it's still less than 7, we'll do it all over again.
C++ is an expansion of C which includes "objects." That means you can define a thing, together with all of it's attributes and the relations between them, and then call back to that object later, as well as modify parts of that object.
Every time we go up a level from the processor, we lose efficiency. When I write 5 lines of C++ code, that might become thousands of bits of machine code once the compiler has done its job; maybe if I had been working in assembly, I could have gotten the job done in a hundred bits of machine code. A more abstract language that C++ would likely be less efficient still.
So now we come to why C++ is still popular. First off, languages aren't static things that are invented and forgotten. The most recent C++ standard, C++11, came out only last year. Secondly, a program written in C++ is incredibly portable - there's virtually nothing that can't run a C++ program. Thirdly, it strikes an excellent balance between efficiency and understand-ability - given that most programmers today find C++ to be powerful enough for all their needs, there's not a lot of pressure to develop more abstract, less efficient languages. Fourthly, because C++ has been so popular for so many years, people have developed an enormous number of libraries you can add on for specific purposes.
By the way, you're right, there are absolutely some languages which are better than C++ for some coding applications. For example, the largest variable you can declare in C++ is 64 bits, at least in a standard implementation. But in Python, not only can you declare longer variables, you don't have to declare them at all, at least not their length - the compiler automatically gives them as much memory as they need.
17
u/raygundan Oct 17 '12
Tenome is right on the money, but I'll try to rephrase and elaborate just a little as well.
"Advanced" is a pretty ambiguous word. You're thinking of it as a synonym for "fast code," but it could also mean "easy to write" or "runs on any hardware" or any number of things.
The fastest code is written directly in machine code. Machine code is the set of instructions the CPU itself uses, and is different between types of CPUs. Code written in a compiled language like C is translated into machine code by the compiler.
C/C++ are "old," but they were designed as a good compromise between ease of writing and reading, and efficient translation to machine code, favoring performance. Their age also means that the compiler tools are very mature and well-optimized, so a lot of the little tricks a programmer might do directly in machine code are done automatically by the compiler.
Other types of languages concentrate on being advanced in other ways, often by automating some task that is difficult or time-consuming in a language like C-- memory management, porting to different CPUs, etc...
But although the code is easier to write, the tradeoff is that it is often not as tightly optimized or as fast.
So when a programmer is faced with a task that demands high performance, they choose the language that lends itself to high performance. When performance does not matter as much, they will choose a language that makes their task easier to complete.
To use some horrible analogies:
Machine code/Assembler is like an F1 car. Driving it requires that you keep track of a million manually-controlled variables. Doing anything at all with it requires quite a lot of skill, time, and money.
C/C++ are like a manual transmission NASCAR. Driving it requires that you have some skill and manage some extra stuff, but it's a lot simpler than the F1 car. Driving it well is still difficult, but it can also be picked up and driven reasonably by anybody who can drive stick.
Something like Java is like an automatic. Driving it is easier, and you never think about the transmission... but you trade off some performance for the convenience. Your grandmother can drive it.
8
u/Platypuskeeper Physical Chemistry | Quantum Chemistry Oct 17 '12
C and C++ are two different programming languages. C++ is a bit newer (going mainstream around the late 1980s) Neither are really that old though, as they've both undergone changes and had features added since they were first created. (And of course, newer isn't always better)
Popular OSes exist in both languages. Linux is exclusively C (its creator Linus Torvalds is strongly against having C++ in it). From what I gather, Windows uses both (as C++ can be combined with standard C code).
Now, operating systems are by definition quite 'low level' code. They provide the basic interface between software and hardware. So it's usually desirable then, to have a fine-grained control over what's going on at the hardware level. You'd get the most control if you wrote in machine code (assembly language), but that's entirely machine-specific, and would mean your operating system would have to be completely rewritten to run on different hardware. So you tend to want to strike a balance between something that's higher-level in order to be portable, but low-level enough to give you a lot of control over what's going on. If you write an OS in a high-level language, you're effectively delegating much of that to the compiler program that turns your code into machine code, and to the libraries of the programming language.
When it comes to application software, there are other reasons. First, lower-level programming languages have some benefits; it's often possible to write faster code in them (although writing in a low-level language in no way guarantees that your code will be faster). As Tenome pointed out, C++ is quite flexible in that it there are large libraries of existing routines that can be used, which effectively make it a fairly high-level language.
Another factor is momentum. A lot of existing programs are written in C/C++, and it's seldom worth the effort to rewrite a large program in another language for the relatively small potential benefits. There's also a lot of programmers who know C/C++, and people tend to be a bit unwilling to learn a new programming language because it's better for a particular purpose. If they're new to the language, they might not be able to fully exploit its benefits anyway. Also, if they don't know the language, they may simply be unaware of the potential benefits.
There's a business side to that, too. It doesn't really matter if programming language X is better for your task, if you can't find programmers who know it! If you can write a program 10% faster in X but have to pay the programmer 20% more because it's a rare skill, that doesn't make good business sense. So economics favors the existing and popular languages.
If you look at language popularity statistics, C and C++ are in the top 3, accompanied in the top 5 by Java and JavaScript, which have relatively similar syntax. Languages like Haskell and Lisp, which are quite different and can do certain things much more simply/elegantly are rather unpopular. So despite the fact that they may be a technically better choice in a lot of situations, they're not necessarily a better business choice.
6
u/PastyPilgrim Oct 17 '12
Just as a quick note because everyone is correcting your usage of "C+" I thought I would explain why it is "C" and "C++" as "C+" is not a language.
In some programming languages, the usage of "++" is used to add 1 to a value. There are a few different ways to add 1 to a value, because that is a pretty common practice (for counting and whatnot), including:
a = a + 1
a += 1
a++
All of those perform the same task (in the languages that support them [for example, python, a popular modern language, does not support a++])
Anyway, back to the point, C++ is a modified version of C that is named as such because it describes C being added to. Just a little tidbit to enhance your knowledge pool.
8
u/[deleted] Oct 17 '12
Don't forget, us advanced physicists and nuclear applications engineers still use FORTRAN for everything.
4
u/utorrent_programmer Oct 18 '12
C is very easy to interface with the raw machine, because you have control of how things are laid out in memory. It is also easy to call ASM from C, and C from ASM.
Note that many OSes are written in C - Linux, ReactOS, and I'll bet many parts of the NT kernel are restricted to their local C flavor.
Most VMs are also written in C++ (note: LuaJIT is written in assembly!) These are applications that must be fanatical about performance; their inefficiency would be multiplied, because we run systems on top of them (other programs and operating systems).
I enjoy that you typed "C+", instead of C++, because from my point of view, that's what the majority of "C++" programs are - somewhere between C and C++. C++ is ever evolving, and frankly, I don't think any C++ program will EVER be "Bjarne approved" C++ - using all the highest level features. It takes time for compiler to properly support the new features.
As for utorrent, it was originally written in a very C-heavy dialect of C++ by a very smart man who was used to writing tight, efficient code. For a person like that, who has such a thorough understanding of the machine, knowing that he was wasting machine cycles would definitely cause him pain.
When you are programming, there are lots of kinds of "power", but there are two which are very important - how fast your program will run, and how long it will take you to write and debug it. Check this out: http://shootout.alioth.debian.org/u32/code-used-time-used-shapes.php
For the first, almost no language can beat C and C++, although many come close (Ocaml, Java (in certain cases), Haskell). For the second - how fast can you write this program, there is almost nothing worse than C and C++. In fact, in these languages, it is very easy for a novice to actually retard the development of a program - wasting more development time than the benefit they give to the codebase.
Hope that was useful!
3
u/SatOnMyNutsAgain Oct 18 '12
C is pretty close to the instructions that your CPU actually executes. The shortest C statements may compile to just one or two instructions, indeed one of the hallmarks of a good instruction set is that it is "C" friendly. C supports just the basic things: arithmetic, logic, conditionals, loops, and moving data around, although more complex operations can of course be contained in a function or macro. Operating systems (I'm talking about the kernel here) have to deal with relatively "primitive" functions like allocating memory, talking to peripherals, copying blocks of data from one place to another, and speaking network protocols. To implement such tasks requires the developer to be very specific about what the CPU is to do, in order to ensure that those things are done efficiently. For most purposes, C gives effectively the same level of specificity as machine code, and indeed there is very little machine code in a modern OS - usually that is only done where you have to do something special for a particular CPU.
Higher level languages like Perl, Python, Ruby, Java etc provide many more features which make "userland" programs easier to write. But they're not very good for writing operating systems because they will always be slower than the same code competently written in a more minimal language like C. But even those higher level languages themselves are usually written in C, just like an OS.
C++ is sort of in the middle. It's not used for kernels as far as I know, but many operating systems use it for higher level but not-quite-application-level stuff like your file browser, print spooler, etc.
Some applications can be painful to write in C. If you're writing an e-commerce system, you don't necessarily care what exact data structure is used or how memory is managed, in which case having to think about pointers and data types can be a huge distraction and a waste of time. But in a kernel you do have to be really explicit, because you are writing the glue that sits between those high level things and the very low level operations of the hardware.
Really your computer runs a whole hierarchy of hardware and software which can be viewed as various tradefoffs between brutal efficiency versus ease of implementing more "civilized" tasks. Not that a kernel is unsophisticated, quite the contrary - but it does require extremely high efficiency despite its complexity, which is what makes kernel programming relatively challenging compared to say, web apps.
5
u/RecursiveRecursiv Oct 17 '12
It is C++.
I will give you three technically precise reasons why:
C++ and C both have pointers that allow access to arbitrary region/section of memories that can be then treated as variables. This allows an Operating System programmer to easily program hardware. When a computer boots up, yours hardware will usually hand over control to a specific region of memory somewhere -- it is easy using pointers to hook this memory and attach a function to it launching your grand schemes.
The C/C++ family makes this easy and this is the single biggest reason why they are still used in OS and systems programming.
In C++/C you can even chose to treat a region of memory as a different entity in one section and then treat it as another variable with completely different type. C makes this easy. C++ makes it a little harder but still do-able.
You can embed assembly code directly into a C++/C program. So you can quickly initialize a hardware and jump back into regular coding.
Compilers for C specially are well-understood and very optimized for their hardware that they usually have a very low overhead for the executables. This allows time-sensitive initialization to occur properly.
Note that C++ and C are technically not portable languages. A non-trivial program written in C++/C for a particular system usually cannot run without modification on some other system.
However, the standard libraries and ubiquitousness of C++/C compilers on systems ensures that all of that system-level difference is completely hidden away from the user. So that header files:
Yeah that file is different or can be different on different architectures.
5
u/Intrexa Oct 18 '12
Holy shit I got this one so hard. First for everything I suppose. Also, spoiler, the core of the operating system (the kernel) is written in C, with some assembly (C is older then C++, assembly is pretty much going back to the beginning).
First, you need to understand the terms "high-level" and "low-level", and how they related to the computer actually doing what you tell it to do. At the (almost) lowest level is assembly, and you are right there pretty much speaking the language the computer can understand (not quite, but pretty close). There is nothing between you and running processes. Everything you need to get done, you can code it to get done. Every one line of code you write in assembly is literally one instruction the cpu does. If you want the computer to do a very specific thing, in a very specific way, you need to use assembly. This is the highest point of efficiency you can possibly attain. No one has, or will write a more efficient language, just by intrinsic definition. Unfortunately, this takes a shit ton of time and work. You also need to know pretty much every little detail of how pretty much everything works. So they made what is referred to as a "high-level" language. This uses (this is the most important term of this entire comment) abstraction.
Abstraction is taking a step back from what you are trying to do, writing in a way that is more easily understood by humans, and letting a compiler turn that into something the computer can understand. So you can still do specific things, but exactly how the compiler tells the computer how to do it might get lost in translation. This means inefficiency. It will still get the right answer in the end, but it might take a bit of a more roundabout way then if you told it exactly how to do it. The higher the level of abstraction, the more high-level the language is, which means you are getting further away from actually telling the computer exactly how you want it done. This makes it easier to program large swatches of functionality, but it also means that you are losing control on how efficient your program can be.
Python sits very high up there in this regard, to display something on your screen, the only line you need to write is: "print 'Hello World!'". With Python2.x installed on your computer, you save that as xxx.py and it will run as a complete program. To do the same in assembly would be a lot more lines, and a lot harder to read. And this isn't even really from scratch, it's calling on a lot of Windows functionality.
Up until this point I have been talking about 'compiled languages', that turn into assembly the computer can understand, and then run it. Even more abstract than that is what's called an 'interpreted language', which uses a 'vm' or 'interpreter' to translate this high level of code into a series of commands that the interpreter running on your OS can understand, that it can then do the correct thing. This pretty much precludes you from creating an OS in these languages; they rely on code already running for them to work (I mean, technically you could create a cpu very specifically for this purpose, but it would be completely incompatible with 'normal' programs and OS'es, while still not being as efficent). So anything that needs an interpreter can't possibly make an OS, because it needs code running to run your code, and if you write the code for that, then you would need code running to run the code running your code, which would need it's own code to allow that. It's a set of all sets problem. Just a short list of languages that are interpreted: Java, Python, Ruby, Javascript, PHP, LUA. These all can't create an OS because they need the OS so they can run.
Now, with that said, if you follow along so far, I can in this paragraph why C remains so popular. C is a bridge between high-level and low-level languages. You are brushing against the bare metal of the cpu. You have the advantages of a high level languages in that they can code large a lot of functionality with a little code, but you can also hammer down and pretty much spell out how you want things done when you need to. A lot of languages can't directly address memory, which C can. A lot of languages can't be like "Give me 20KB of RAM, and I'll use it for whatever I want to", they are more like "Can I please have some memory to store some letters? Thank you". And, when push really comes to shove, you can section off a block of code to actually be written in assembly when you really need to be as efficient as you can get. You can write exactly what you need to, and it comes out exactly as you need it. To write a Windows driver (things like printer drivers, or video card drivers), you literally need to use C. It is the only language that can fill out all the ridiculous requirements that are needed to make a working driver, with the most important being able to create small page size the CPU demands it. Technically C++ can fill the requirements, but you will be jumping through a lot more hoops, and you're already jumping through a lot. It's at this point I hope you can appreciate the joke "An OS architect changes career paths and starts selling furniture at IKEA. A new shelf they sell uses the wood from driftwood. He labels the box 'Made in C. Some assembly required."
C++ sits a step above C. It was designed to provide more high level abstractions on top of C. It actually includes all of C's instructions, but also creates new ones. But, as detailed earlier, when you use these high level abstractions, you are getting further away from direct control. C++ is still very fast, and very efficient, but when you start using some of the new things added, it makes the executable bigger, it makes it a tad slower. If you need to get the speed back, you can still write C in C++ for where it counts, or assembly for where it really really counts, but it's just a tad slower, and it's still a lot better in speed and efficiency then almost all other languages.
I think everyone else went on about how Both C and C++ have been receiving updates, so I will not cover that here.
Please post questions and comments. Also, if your name is Carl, Fuck you.
2
u/ShakaUVM Oct 18 '12
Master's degree in computer science here.
There's no C+. Programs are written in C or C++.
The nice thing about C is that you generally get to see everything that's going on. Languages like Java obfuscate what is going on, and are a bit slower, though JIT compilation and fast CPUs make this mostly a moot point. Some people like garbage collection memory allocation systems, too, but there's advantages and disadvantages to it.
There's good libraries for most things you need to do in C/C++, so the matter of "more powerful code" kind of works in reverse - there more stuff available for C/C++ than for pretty much any other language.
There's only a couple areas where C/C++ shows its age - namely in parallelism (my master's thesis was in HPC) and in certain forms of inheritance and type polymorphism. You can do it, but it's clunkier than with more modern languages.
2
u/thekaldar Oct 18 '12
First, most operating systems are written in C, not C++. The reason operating systems are written in C is because it is actually the most powerful language out there, besides things like machine code(the code used directly be the cpu, 1s and 0s). C was designed to be very fast and work directly with the computer, and also works on almost every. C++ isn't used, because it is higher level, and requires an operating system already on the computer to perform a lot of tasks.
2
u/[deleted] Oct 17 '12
Programs are written in a variety of languages, but as for operating systems, most use C or C++ because these languages allow inline assembly-code, which is necessary for the glue between the bootloader and the kernel at the very least.
Edit: Clarity.
1
u/MdxBhmt Oct 18 '12
I'm probably repeating what everyone's saying but here my quick especulation:
Most newer language are harder to find developers for, so you cannot make a big project that requires dozen of programmers.
It is also important to know that older mainstream languages have much more mature compilers, codebase and etc, which is solid advantage (against a maybe newer language that LOOKS like have better abstraction, not-so-solid evidence for an advantage). Management will rather pick an old proven technology than the newer unproven tech.
Second, big companies take the code reuse seriously, like windows having pieces of code literally untouched in ages, since this codebase is in C/C++... Why change?
PS: I disagree when people say that C++ is not that old since is being patched all the time. The language is in essence the same, the syntax/how you code it will be similar, as the pitfalls.
C++ also has some philosophy while making extentions like backward compatibility (old code must work on newer version) or 0-overhead abstractions features, that have it's pros and cons.
//Disclaimer: Control Engineer Student, not CS. Learns Haskell as hobby.
1
u/Chi11out Oct 18 '12
I think it's mainly due to hardware for it isn't really being drastically changed(so no one is getting blown out of the water). In most cases you're simply making hardware faster or building upon preexisting technology so the fundamentals don't really change that much. Now if something was built from the ground up using a drastically different scheme to things for example maybe something other than binary it could prompt a paradigm shift in the way problems are solved. So a new language could be used or created opposed to reshaping/modifying/updating an existing one.
1
u/katzey Oct 18 '12
This thread makes me so excited to study computer science in college.
0
u/balefyre Oct 18 '12
At least do enough homework to communicate your question properly. I'd say that's what the internet is for, but....