431 points · by daschl1 · 13y ago · 384 comments
A more realistic view of C:
- C is straightforward to compile into fast machine code...on a PDP-11. Its virtual machine does not match modern architectures very well, and its explicitness about details of its machine mean FORTRAN compilers typically produce faster code. The C virtual machine does not provide an accurate model of why your code is fast on a modern machine. The social necessity of implementing a decent C compiler may have stifled our architecture development (go look at the Burroughs systems, or the Connection Machine, and tell me how well C's virtual machine maps to them).
- C's standard library is a joke. Its shortcomings, particularly around string handling, have been responsible for an appalling fraction of the security holes of the past forty years.
- C's tooling is hardly something to brag about, especially compared to its contemporaries like Smalltalk and Lisp. Most of the debuggers people use with C are command line monstrosities. Compare them to the standard debuggers of, say, Squeak or Allegro Common Lisp.
- Claiming a fast build/debug/run cycle for C is sad. It seems fast because of the failure in this area of C++. Go look at Turbo Pascal if you want to know how to make the build/debug/run cycle fast.
- Claiming that C is callable from anywhere via its standard ABI equates all the world with Unix. Sadly, that's almost true today, though, but maybe it's because of the ubiquity of C rather than the other way around.
So, before writing about the glories of C, please go familiarize yourself with modern FORTRAN, ALGOL 60 and 68, Turbo Pascal's compiler and environment, a good Smalltalk like Squeak or Pharo, and the state of modern pipelines processor architectures.
I'm confused when you speak of a virtual machine with regard to C... can you explain what you mean by this?
I had to wikipedia the Burroughs machine. I guess the big deal is that it's a stack machine? It looks very interesting and I plan to read more about it. But I guess I don't understand why that is a hindrance to C.
The JVM is a stack machine, isn't it?
btw, I haven't read the article yet. It's my habit to check comments first to see if the article was interesting, and seeing your comment made me want to reply for clarification.
C defines a virtual machine consisting of a single, contiguous block of memory with consecutive addresses, and a single core processor that reads and executes a single instruction at a time. This is not true of today's processors, thanks to multicores, multiple pipelines, and layers of cache.
There is no requirement in C that you be able to execute data.
You certainly could have a C implementation that bounds-checks strings and arrays. (See e.g. http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html for a very old paper on how you might do that)
The "abstract machine" of C explicitly does _not_ make reference to the memory layout. (cf 5.1.2.3 of the spec)
It also makes no reference to the number of cores, and order of execution is not one at a time, but limited by sequence points.
That's the whole point of C - it is very loosely tied to actual hardware, and can accomodate a wide range of it, while still staying very close to actual realities.
Edit: Please don't take this as a "rah, rah, C is great" comment. I'm well aware of its shortcomings. I've spent the last 20+ years with it :)
This is 100% false. The C standard makes no mention whatsoever of memory. I don't know much about the burroughs machine, but it sounds like it would map very well to the C virtual machine:
C permits an implementation to provide a reversible mapping from pointers to "sufficiently large integers" but does not require it.
A pointer to an object is only valid in C (i.e. only has defined behavior) if it is never accessed outside the bounds of the object it points to.
Converting between data pointers and function pointers is not required to work in the C standard either.
C does require that you have a NULL pointer that has undefined behavior if you dereference this, but this could be trivially done by the runtime by allocating a single unit of memory for it.
Which is true, for a rather stretched definition of "virtual machine"(which falls apart at the kernel level, because it's pretty hard to work with a machine's abstraction when you're working directly on the hardware).
The problem with the virtual machine comparison is that C doesn't mask ABI access in any meaningful way. It doesn't need to, since it's directly accessing the ABI and OS. So the argument that C isn't multithreaded is rather shortsighted, because C doesn't need that functionality in the language. It's provided by the OS.
However it speaks of a compiler for ALGOL... it was compiled down to machine instructions. Assembly is just a representation of machine instructions, so I don't see how it can be said to not have an assembly language.
Maybe nobody ever bothered to write an assembler, but that doesn't mean that it somehow directly executes ALGOL.
Thanks for your replies, you have given me some food for thought.
[1]http://en.wikipedia.org/wiki/Burroughs_large_systems_instruc...
This type of machine has become so ubiquitous that people have begun to forget that once upon a time, other types of machines also existed. (Think of the LISP Machine)
I'd guess that the virtual machine of C pertains to the addressing and the presentation of memory as a "giant array of bytes". Stack addresses start high and "grow down", heap addresses start low. These addresses need not exist on the machine. For example, two running C processes can have 0x3a4b7e pointing to different places in machine memory (which prevents them from clobbering each other).
Please, someone with more knowledge than me, fill me in on where I'm right and wrong.
You are also confusing multitasking/multiprocessing with C. C has no such concept (well, C11 might, I haven't looked fully into it) and on some systems (like plenty of systems in the 80s) only one program runs at a time. The fact that two "programs" both have a pointer to 0x3A4B7E that reference two physically different locations in memory is an operating system abstraction, not a C abstraction.
Turbo Pascal vs C? Really? In its time Turbo Pascal was an amazing piece of software but in the grand scheme of things it is a pimple compared to the whale that is C. Please compare all software written in Turbo Pascal as opposed to C if you have any doubts. The same goes for Smalltalk, Lisp, Algol 60/68. All great products/languages but very niche.
Fortran can be faster than C in some areas but again it is a niche language.
I could go on a lot more but quite frankly I don't think your post merits much more discussion and is borderline trollish.
C as a very thin virtual machine is a common conception and not an incorrect one--C runs on many systems with noncontiguous memory segments but presents it as a single contiguous space, for example. The idea of C as a virtual machine is much of the basis of LLVM, and to the best of my knowledge I've never worked on a computer where C represented the underlying hardware without significant abstractions.
If you're going to accuse somebody of trolling, you should know what you're talking about first.
I have worked extensively in the past with C and have never heard it referred to as a virtual machine, thin or otherwise. I understand that the OP probably means "computation model" or something similar but felt that the use of the phrase "virtual machine" was a bit on the bombastic side and that in addition to the general tone of the post made me think the post was borderline trolling.
BTW. I would be quite happy to be proved wrong about C commonly being referred to as a thin virtual machine - what books/literature refer to C in this way?
C does no such thing. That is the job of the MMU, and C has nothing to say about it. You're going to have a hard time convincing anyone that a language without a runtime somehow has a VM. That's nonsense.
CPU's and operating systems go to substantial lengths to present programs with a "C machine" on modern hardware. Your multi-core CPU doesn't look like a PDP-11, but it uses reorder buffers to make execution look sequential and cache coherence built on message passing to make memory look uniform.
Note that the C language standards are written in terms of an "abstract machine". For example, "When the processing of the abstract machine is interrupted by receipt of a signal, only the values of objects as of the previous sequence point may be relied on" from 5.1.2.3.
Granting that, I can't say I agree with his point: C has probably ran on more machines than any other language. As an abstraction over machines it is, if not perfect, clearly good enough.
All true, but how are you going to implement a single project using just the best parts of FORTRAN, ALGOL 60, Turbo Pascal and Smalltalk?
It's that I used to be able to sit down at any Unix machine in the world, shove some code into an editor, call some system libraries, get it to compile, and maybe even step through it in a debugger, and go home at the end of the day, and I could do that because that's what its designers were doing with it, so they made sure that all of it at least functioned at a good enough level to get through the day. Not always anymore, since a lot of Linux distributions no longer install the C compiler by default.
C compilers let you specify that you want similarly relaxed semantics via compiler flags and language keywords; however, they also allow the programmer to have stricter behavior when necessary, e.g. allowing one to operate on memory that may actually alias and still get correct behavior.
I think the author's criteria for "effectiveness" are very much different from yours, hence the different conclusions.
As for standard library, I learned from K&R and have never been surprised by the library (insofar as I can reasonably predict what will happen, given the guidelines). I cannot say that about the C++ standard library (don't get me started on STL) or Java
And as for debugging, it took me years to become adept at parsing STL error messages (wading through cruft like basic_string to get to the essence of the error).
however I do agree that Borland and turbo pascal are exemplary.
Now, sometimes you need that low level access, but C is used way beyond those niches.
The problem with the standard library is that it is tiny and its basic types are often ill designed. Certainly it's fairly consistent, and so fairly unsurprising, but that's not the argument.
The use of the term 'virtual machine' for C is appropriate in the case of an individual wanting to purposefully show that he has a 'better' handle on the semantics, and that a mere mortal surely would not understand his glorious knowledgs.
Since the 70s or 80s, CPUs have gotten a lot faster while memory access has only gotten incrementally faster. This means that CPU manufacturers have put an increasingly sophisticated caching system on the CPU die to speed up access to main memory contents.
C's simple model allowing pointer arithmetic, aliased pointers that overlap to the same memory, etc, mean that compilers can't produce the optimal cache behavior on the CPU, because they can't reason definitively about when a given region of memory will be accessed based on the variables being accessed (pointer might have been modified or might overlap another one). They also have trouble invoking things like SIMD instructions which do math quickly on vectors. Fortran, with stricter rules about arrays, is more conducive to this.
Furthermore the vast majority of languages allow free aliasing, differing from C in what things pointers are allowed to point at and not in the number of pointers which may point at them.
However, it is here to stay, just like Inch, Foot, and Fahrenheit. Not that the alternatives are worst, just the cost of switching over and training a whole lot of people is back-breaking.
Note that most unfortunately, it is being taken over by javascript (false == '0'), which is a far worse language in many aspects.
Nothing is straightforward to compile in to efficient machine code, and FORTRAN is not at all easier than C. Many compilers (e.g. GCC) use the same back-end for FORTRAN, C and other source languages. FORTRAN's clumsy arrays are a little nicer to the compiler than C's flexible pointers but the "restrict" keyword solves this.
> - C's tooling is hardly something to brag about, especially compared to its contemporaries like Smalltalk and Lisp. Most of the debuggers people use with C are command line monstrosities.
Yes, C debuggers may be a little clumsy compared to modern source level debuggers. But you can plug gdb in to almost anything, from a regular user space application, a microcontroller chip like Arduino, a kernel image running in QEMU, remotely debug Win32 code on Linux, a live CPU with a debugger dongle, etc.
> - Claiming a fast build/debug/run cycle for C is sad. It seems fast because of the failure in this area of C++. Go look at Turbo Pascal if you want to know how to make the build/debug/run cycle fast.
What's the point in compiling slow code quickly? Turbo Pascal was not really a good compiler, especially if you'd compare the output to a modern compiler.
Also take a look at the progress going on with LLVM/Clang/LLDB, they're working on better debugging and REPL-like environments for C.
In addition, many CPUs provide prefetch instructions to make sure data is in cache before it's used, or cache-skipping loads and stores to prevent polluting cache with data that's only ever touched once.
https://en.wikipedia.org/wiki/Cache_timing_attack
If you can exploit the effect that cache has on latency, it is reasonable to assume that you can manipulate it in other ways.
C is straightforward to compile on pretty much every single CPU out there. A C compiler is required to certify many very common CPU's before they go into manufacturing, in fact. You cannot go to silicon, in many fabs, unless you have demonstrated the CPU can handle code; most of the code doing all this testing, is in C (lots of Assembly too). C is a front-line language, at the fabrication level.
- C's standard library may be sparse, but the diversity of other libraries out there means that you can do your own thing, and have complete control over what gets packed into your final binary image. This is a given, because it is powerful. A scan of /usr/lib,/usr/local/lib, or a search for .so/.dylibs in /Applications, for example, gives me, quite literally, nothing I can't like to with a C compiler.
-My fast edit/build/run/debug cycle goes like this: hit the hot-key in my editor, watch output, done. Of course, I also have periods where I must sit and compile a larger collection of libraries; usually at point breaks in my development cycle, but this is all taken care of by my build server, which runs independently of development servers. With C, I've been able to easily scale my build/release/developer binary packaging requirements from "needs to be instant interaction between new code and running tests" to "needs an hour to generate keys and dependencies and be prepared for a solid few years of use". C's build time scales according to the productivity of the developer.
-C is highly productive, if you do not trip over key things. Yes, building your own libs package should be a core part of professional C competency; no decent C developer worth their salt, who can't add a few lines of code to a multi-million-line codebase and figure out how to not sit there waiting for the kettle to boil while it builds for testing, should be allowed in any production environment. A proper C Makefile can build entire operating systems-worth of applications; for domain-specific apps, I hardly even notice the build time any more, in between edits and updates. C code is built so fast and integrated so well in repository/testing tools, that in my opinion the system is so well integrated its not relevant.
Now, if you need a prepackaged thing, and don't want to hassle with needing to know how to assume an iron grip over the dependencies issue, then of course C is a big hassle. Other languages have their time, and place.
You know what else I like about C? Lua. With C and Lua, and a careful selection of optimal libraries, you can build a development environment beyond compare in any other realm. The pure joy of understanding how a table-driven application goes from:
work_q = {} and work_q = { {name="empty trash", when=os.now(), msg="The system trash is emptied.."}, {name="copy file", when=os.now()+1000, msg="A backup is being performed..", cmd="tar -cvf /mnt/backups /home/*"}, }
.. to a working C-layer on multiple platforms, all functioning exactly the same way, all working from a single binary .. well then, this joy is greater than many other language/systems of development.
Welcome to C in the 21st Century.
Basically C is where it is because of a combination of timing and market forces. Market forces are usually underestimated by theoretical computer scientists, but they have a much stronger say in the success of a language than anything else.
However I still believe knowing C inside out is an essential skill, and as bad as it is, it's better than most of the alternatives for "low level" code. They usually either try too hard to be different or don't offer enough to substitute C and all the traction, coders, literature and codebase around it. And, as you mentioned, the fact that architectures became historically forced to play nice with C's machine abstraction.
Titles to some papers or some comparisons on a mailing list would be awesome to have if you know any off the top of your head.
the idea that specific requirements of c had started driving architecture development blew my mind the first time i came across it. it is still a point that does not get discussed nearly enough at a popular level.
Only in extremely limited contexts: low-level code for operating systems that happened to have been written in C. Otherwise, there is a better language for pretty much every use-case of C.
Any good alternatives to C?
You say that like it is an accident that just about every major OS today is written in C or C/C++
Nonsense. This sudden C fad is totally baffling to me. C is a great language for low-level work and it does have an attractive minimal elegance but is in absolutely no sense of the term a high level language. A language with next to no standard containers or algorithms, manual memory management, raw pointers, a barely functional string type and minimal standard library and concurrency primitives is just the wrong choice for any application that doesn't need the kind of low-level control C provides.
Go ahead and jump on the bandwagon but don't come crying to me when you wind up with an unmaintainable mess riddled with security holes and fiendishly subtle memory errors.
Of course it is. You're not worrying about how many registers your CPU has, or when you swap a register out to memory. All that has been abstracted away for you. The fact that you can access memory locations directly gives you some low-level access, but in a very real sense C is a high-level language. There are higher-level languages with more abstraction, of course. From the article: "It's not as high level as Java or C#, and certainly no where near as high level as Erlang, Python, or Javascript."
At the very least, it's something like a medium-level language. Grouping it with much higher-abstracted languages is just wrong.
It's fine if you want to call "high-level" relative. But it should be acknowledged that "high-level" is not simply a strict comparison between the features of one language and another. And it SHOULD be acknowledged that C is, by convention, a high-level language. Python is definitely a higher-level language, but C is still a high-level language.
Now grouping Java with Haskell, that doesn't seem like a reasonable grouping.
Of course, it's all swings and roundabouts really. You can draw lines anywhere.
Just like diamonds are no longer at the top of the mohs scale. C is no longer anywhere near the top of "high" in "High level" languages.
Langauge itself is a highly variable thing. People can understand something completely different from what the originator intended, but it doesn't change what said originator meant by it. People can always say "oh C is not a high level language because I think that a low level language should be X and Y" the same way they can say "oh men have to have a beard and know how to fight to be be real men", but in reality men - beards or not - are still fundamentally men.
There's machine code, low level languages which are basically the plethora of different Assembly languages, and high level languages which provide abstractions to either or both of the former languages and resemble the actual written language. Putting C in the low level languages rank is doing a disservice to the language and not taking into account the bunch of people that program (for example) embedded devices in whatever architecture they're using.
C is the Latin of the modern programming world.
But you need to worry about size of registers. How many modern languages have basic data types without strictly defined sizes?
Here's a non-obvious example. With C, the programmer must always be aware of evaluation order. In fact, this must be specified even in cases where it is not important. For example:
x = a + b;
y = c + d;
Since the values x and y don't depend on each other, they could each be calculated in any order. However, with C, the programmer must explicitly decide on the temporal order that x and y are calculated (the order they appear in a function), even though it doesn't matter. And yes, the C compiler may decide to re-order those calculations under the covers as it decides (for performance reasons perhaps).With Haskell, when you are outside I/O Monads and such, you don't specify the order of calculations like the above. Those two calculations may appear in that order in the source code, but the Haskell programmer knows that doesn't mean anything. The system may calculate x first, y first, or perhaps neither if those values aren't actually used elsewhere. Temporal ordering is not necessary (or desirable) under most circumstances.
You can never forget about temporal order in C, but there are higher level languages that allow this.
Its flaws are very very well known, and this is a virtue. All languages and implementations have gotchas and hangups. C is just far more upfront about it. And there are a ton of static and runtime tools to help you deal with the most common and dangerous mistakes. That some of the most heavily used and reliable software in the world is built on C is proof that the flaws are overblown, and easy to detect and fix.
Security holes in C applications allow for the injection of low-level programs. This is way more annoying, IMO.
also the static and runtime tools for C are good, and getting better, but still very far from being a replacement for writing code in a memory-safe language.
It just there is a lot of C out there which means we will see it for ever in our systems somewhere. It will get better over time as tools improve the existing C code base.
Sure, but it is much, much, much easier to do in C than in other languages. By default you have unchecked array access, fixed width integers, strings terminated by a special character, and tons of exploitable undefined behavior. Writing secure code in C takes substantial effort, substantially more than in other languages.
Look at Microsoft's CVEs for 2012. Approximately all of the serious ones would be impossible with a proper type system. This is after all of Microsoft's static analysis tools and code reviews and security focus.
One problem with the term "high level language," is that it was coined many, many decades ago. C is a "high level language" like FORTRAN is one. Remember, when C was invented, programming via punch cards was still a routine activity in many shops.
This is why the assertion that, "C is a fantastic high level language," or even that it's a high level language at all is so controversial: It exploits a term which is so old, changing expectations have tectonically shifted the programming field into a place where there is an opportunity for surprise and controversy.
There are "high level languages" which are minimal, and those which are not. There are "high level languages" which offer a large amount of abstraction and those which offer less. Right there are two spectra which can be used to classify languages, and C is stuck near the extreme lower left corner. (A minimal language which offers less abstraction.) Then you have languages like Lisp and Smalltalk which are even more minimal, but which offer higher degrees of abstraction. When one says, "high level language," one is talking about a very broad category.
Which is why you can do this: http://news.ycombinator.com/item?id=5037315
The article uses an old standard as a little trick to try to put C in a category it doesn't belong.
There's a string type in C? All I see are character arrays and a few (poorly thought out) conventions for using them.
What I see talking to people and looking at forums (this one for example) is the exact opposite of a C fad. Frankly I wish it were the other way. I encounter fewer and fewer people with C knowledge, and especially fewer people who say they are happy writing C. New college grads sure as hell don't graduate in large numbers knowing C, even if a good chunk of them can churn out acceptable Java.
At the core, a good language shouldn't really have any of these things you say built in - they should be built on top of the language itself.
What language will be used to build the first human-level AI? I think it will probably be C, and less than 1 million lines of code.
I don't think so, but I respect your opinion.
The high-level space still doesn't have a winner and it probably won't for some time. It has a lot of excellent languages that are all radically different (Clojure, Haskell, Python, Scala, Erlang) and each is really cool in some ways and very infuriating in others. C, of course, is really cool in some ways and very infuriating in others as well.
I've taken up learning C, and my feeling about it is that it's not a "jump in and figure it out" language, in the way that most technologies are, because you're absolutely right. Naive or "cargo cult" C is going to be a disaster from a security, code-quality, and production stability perspective.
For most technologies to qualify as safe, sane, and consensual, they have to be secure even when wielded by a programmer who cobbled together incomplete knowledge from a few dozen Internet articles about how to do stuff. Not C. There are "quick adoption" technologies with quick learning curves and "lifer" technologies that are quirky and hard to learn at first but provide long-lived knowledge. C is a lifer language. If you don't treat it as such, you'll faceplant.
That's what libraries are for, numbnut.
Ignoring pre-history (BASIC, FORTRAN, PDP-11 assembler, Z80 assembler, Pascal), I started out in C, many years ago. I found myself using macros and libraries to provide useful combinations of state and functions. I was reinventing objects and found C++.
I was a very happy user of C++ for many years, starting very early on (cfront days). But I was burned by the complexity of the language, and the extremely subtle interaction of features. And I was tired of memory management. I was longing for Java, and then it appeared.
And I was happy. As I was learning the language, I was sure I missed something. Every object is in the heap? Really? There is really no way to have one object physically embedded within another? But everything else was so nice, I didn't care.
And now I'm writing a couple of system that would like to use many gigabytes of memory, containing millions of objects, some small, some large. The per-object overhead is killing me. GC tuning is a nightmare. I'm implementing suballocation schemes. I'm writing microbenchmarks to compare working with ordinary objects with objects serialized to byte arrays. And since C++ has become a hideous mess, far more complicated than the early version that burned me, I long for C again.
So I don't like any language right now.
A side effect of C universalization, especially with open source, is that people forget all about that pre-history. Hacker culture now is mostly C/Unix with a dash of Lisp and Smalltalk heritage.
But from what I remember of microcomputer culture in the early 80s, hackers in the field were doing line-numbered Basic and Assembly language - if you had exotic tastes maybe Forth or something. If you were a Basic guy C was DANGEROUS (my programming teacher spoke of C the way Nancy Reagan spoke of crack cocaine) and if you were an assembly guy C was a slow hog.
And if you had access to a "real" computer, chances are it was running PL/I, COBOL or Fortran, not C.
The 1983 video game Tron had levels named after programming languages: "BASIC", "RPG", "COBOL", "FORTRAN", "SNOBOL", "PL1", "PASCAL", "ALGOL", "ASSEMBLY", "OS" and "JCL". C apparently did not merit mention; its complete dominance didn't come until some ways into the PC era.
In the university UNIX forced me to move to C and later on C++. P2C was the only available Pascal compiler and a joke when compared with Turbo Pascal.
I also left with the impression that it is very early days with Go, in the sense that several parts of the language are evolving. (Or maybe I have this impression because the presenter loved diving into ratholes.)
Unfortunately unless you're on windows it's not that fast compared to Java.
Actually they are doing something like that already with MDIL in WP8.
You mention GC tuning and object overhead so it sounds like there is some high-frequency object creation happening?
- The build system is broken.
vs. make. qmake. cmake. autotools. scons. 'modern' makefiles (>_> what does that even mean? Yes, I'm looking at you Google) There's a whole ecosystem of tools out there to solve this.
- There are a few rubbish IDEs, most of which support c as a second class candidate.
VS has officially abandoned C; xcode grudgingly supports it. The CDT is mediocre. There's little or no support for refactoring or doing other things on large code bases, and the majority of the time the work has to be done manually.
- Because the build system is broken, dependency management is hell
Got one library that uses scons, another using autoconf, and what to build a local dev instance of a library without installing it into the system path? Goooood luck.
This is made even worse by arcane things like rpath, which mean that dynamic libraries only work when they are in specific paths relative to the application binary (I'm looking at you OSX).
- Its a terrible collaboration platform.
Why? Because the barrier to entry is high. To submit a patch that works and doesn't break other things, doesn't introduce serious security holes or memory leaks is hard.
Astonishingly, some successful projects like SDL are actually written in C, but most C projects are not collaboration friendly.
- There are no frameworks for doing common high productivity tasks in C, only low level system operations, or vastly complicated frameworks with terrible apis (>_> GTK).
I'll just whip up a C REST service that talks to mysql and point nginx at it. Um... yeah. I'm sure there's an easy way to do that. ...perhaps...?
How about a quick UI application? We'll just use GTK, that's portable and easy. ...Or, not very easy, and vastly complicated to setup and build.
These issues aren't unique to C, but they're certainly issues.
I'm not really sure I'd happily wonder around telling people how amazing C is at everything.
It's a tool for some jobs; definitely not all.
I'd completely agree. I would not use C for doing any web platform work (writing a REST service as you say). I may write a webserver in C if I had tight memory constraints.
Where I see C still being very useful: embedded applications, drivers, and latency sensitive code.
When you are trying to push the most I/O possible through a network interface or disk interface, C allows extremely tight controls on memory and CPU usage. Especially if you are coding to a specific CPU for an embedded product, you can really tweak the app to perform as required (though, this may require some assembly to do what you need).
Search for libfcgi. It's nice and simple C library that can be used behind nginx and as the matter of fact anything that supports fcgi. In this case routes are defined on nginx. But just think a bit, it's nice little framework ;-)
Btw used exactly that few months ago.
When I use python extensions (often written in C), this problem doesn't arise because distutils, and sometimes cython, handle everything.
Python isn't the best C build system, but frankly it scores better than cmake and friends for ease of use.
std::map<std::string, std::vector<std::string>> foo;
One line and you've set up a nontrivial data structure with automatic memory management. No macro horrors (which are a diabolical way of implementing what C++ templates do well).Since you can code like C in C++, I'm not sure why more people don't use C-with-templates as a programming style.
Whenever I see younger people gushing about C, I can't help but wonder if they've actually written anything nontrivial with it. When used properly, C++ is a vastly more productive language.
You aren't going to run out of lines any time soon. Who cares whether your data structure definition is 1 line or 5?
I must say I laughed-out-loud at that, mainly because I've been on both side of the divide when it comes to opinions on verbose std definitions. It is an odd feeling to simultaneously feel revulsion and nostalgia towards a line of code.
I do think there is a non-trivial, and sometimes massive boon gained from concise definitions. It's the difference between an acronym in natural language vs referencing a concept by its full verbose name. The shorter the definition of a concept, the fewer units used by your working memory when referencing that concept, thus freeing your mind to higher level considerations.
I discovered the STL one day in February 1999, by accident, when looking for something else in the VC++ help. Once I realised what I'd found, I gave up C entirely within about 1 week.
using namespace std;
map<string, vector<string>> foo; // foo.h
typedef std::map<std::string, std::vector<std::string>> StringToVectorString;
// foo.cpp
// in several places you can just use:
StringToVectorString foo;Why not use assembler and make it 50?
Today, I'm looking at C++11 and using Clang, and I like what I see. Vastly improved compiler error messages, lambdas, very decent type inference, standardized smart pointers, good standard library (and Boost is always an option). I haven't tried heavy-duty debugging yet, but I suspect it still sucks. Overall — I'll probably be using C++ quite a bit more in the future. It is no longer the nasty pile of kludges on top of C which it used to be ten years ago.
Personally, I use C for my embedded work and Python for test applications and data processing. C++ is in the middle and I haven't had a use for it.
(I like to write my code without heap allocations, but when you need an array of arrays of strings, indexed by another string, it doesn't half get a bit annoying to code up.)
Yes, template programming is not something I am likely to ever figure out but these things only need to be built once, by somebody other than me.
I immediately thought of this: "Go is like a better C, from the guys that didn’t bring you C++" — Ikai Lan [1]
And that's what it feels like to me when I use it.
> C has the fastest development interactivity of any mainstream statically typed language.
What? Despite all its shortcomings, Java in a modern IDE effectively has zero build time. The level of interactivity is as fast as that of interpreted languages. I haven't seen anyone manage this with C yet.
I've been using IntelliJ IDEA for Java development for the last 4 years, and before that I used C and C++ using Emacs for 7 years.
I am way more productive in IntelliJ IDEA than I was before. One reason is the instant feedback on syntax errors when I type the code. I don't need to compile to see them, as I used to in C and C++. Another reason is the navigation support you get in an IDE.
I've written more about the differences in development environment here: http://henrikwarne.com/2012/06/17/programmer-productivity-em...
Java, itself, does not highlight your syntax errors. Nor does C.
There are IDEs out there that will do exactly the same thing for you for your C code.
As a matter of interest, which C IDEs are you referring to? I'd like to check them out.
Every (non kernel) C project I have worked with has effectively 0 build time after making changes. This is because they all used make which (like Eclipse and likely all IDEs) only recompiles the files you changed. However, there is not the startup time of the VM (which for every non Java VM I have seen is also effectively 0.)
As an aside, does anyone know why Java has an unusually high startup time?
For trivial changes maybe. Rebuild time will depend on the size/complexity of the project and the number of dependencies on the thing that was changed.
A change to a header file of a core library may cause a rebuild of many parts of the project thanks to dependencies built on header files. We have such a library in our product and modifying a single file can cause ~40% of the product to need to be rebuilt.
Think about changing something like:
#define VERSION "1.2.3"
which is compiled into every library and binary within the product.JRebel is also worth investigating if you are getting paid to work with java code.
C does not have or need a Repl because it's not designed for giant single programs anyway. Unix is the C Repl.
I noticed in another comment you said you are just learning C, perhaps you should wait till you have written non-trivial C before you declare what tools one does or does not need when writing it? C makes it very easy to make very nasty mistakes, so personally I take all the help I can get. I guess this means you think I'm an awful developer (according to your recent anti-IDE blog post), but I'd rather have code with less bugs than worry about violating some notion of 'purity' or hacker-hardcorness.
And I mean on the basic language level, not "using a library to run a hot swap VM for my language" level like Eclipse and IntelliJ IDEA do.
2) Figure out something controversial to say about it and a justification for that
3) Write it up and post it to reddit, HN, &c
4) Enjoy the hits
EDIT: Which is enabled by this - http://news.ycombinator.com/item?id=5037649
Someone the other day said that the great thing about C is that you can get your head around it. When Java, or C++, or Erlang, or Common Lisp, or Haskell programming becomes unbearable, it's almost always because the chain of abstractions overwhelms the person building the system. And to be honest, it's why I'm a little less enthusiastic than most of the people here about Rust.
I ran into a bug in an XOrg driver for an old r128 card a few years back. (I think I have that combination right.) As I remember it, I spent several hours tracing through layer upon layer of C macros to even begin to get an idea of what the code was doing. The bug turned out to be part of a structure getting overwritten clobbering a part of a vertex definition with a color value due to a mix up in the size of the structure. (I'm forgetting the details on this and I can't remember the bug number off hand or I'd look it up.)
In any event, those layers of macros made it almost impossible to trace what the heck the code was doing without intimate knowledge of every part layer involved. I'd say chains of abstraction are more a feature of programming style rather than the language itself. Albeit, the language can ease the load a little.
The region system is obviously a source of complexity. But I feel as though sacrificing safety at compile time in the name of simplicity just leads to complexity later—you either pay the complexity tax at compile time, or you transfer the complexity of correct memory management to runtime, resulting in sessions sitting in front of gdb or valgrind.
The common liturgy of language design is that x feature makes development easier, less error prone, safer, etc. Nearly always, the precise way in which x feature does this is as clear as a bell. But somehow, as we multiply the number of features, something truly destructive starts to happen. It's not just diminishing returns . . .
I think about a language like C++. I can see the reasons for every single thing in it. I can understand the arguments for why this or that is a good thing. But it is perilously easy to write very unmaintainable code in this language, and to understand why, I think we have to get beyond the usual debates (static vs. dynamic, functional vs. OO, compiled vs. interpreted, etc). Small vs. large might be one place to start.
A more plausible explanation is that you wouldn't even attempt a similar design in C because it'd be obviously impossible.
On that topic, I'd rather write crypto code in C too.
That would explain why there are so few Haskell programs that anyone actually uses.
If you tried to use your soccer-mom minivan to participate in F1 races, of course you would complain. I can't tune the engine? I can't tinker with the oil pressure?!? How do I adjust performance for different tracks?! This thing sucks. Also it's slow.
These kinds of debates about C and other "higher" level languages are growing tiresome. We live in a wonderful world full of different tools for different purposes. Maybe your grandma doesn't want to worry about details under the hood, and she also doesn't need to race F1 cars, so a minivan suits her just fine. Maybe you value being able to tune your code for maximum speed and you don't mind (or even enjoy) the challenges involved in C code. Good for you.
yawn...
It is for this reason that C (and sometimes C++) are what people use when they have a new idea about higher-level programming abstractions. With C, you can be totally free of other people's big ideas (and their associated costs/complications) and invent something new.
Anyone who wants you to give up C in favor of their language/framework/VM/runtime is selling their own vision for how the world should work. That's fine and sometimes buying in will save you a lot of hassle. But what they're offering was almost certainly written in C or C++. Essentially their pitch is equivalent to "I have written the last C program you'll ever need."
In the early 90s that was Perl. In the late 90s, Java. In the early 2000s, .NET, then Ruby, then fast JavaScript.
This history is an oversimplification of course, but the real question is: would you really prefer a history in which we had, at some point, decided that the current VM that was in vogue should become the new replacement for C? That we'd tailor all our hardware to it, and no future VM would be "native" but would have to run on top of a different VM?
C is the key to why we have general-purpose computers that can run a wide variety of different languages efficiently, and why programs that need to be particularly efficient can always drop down to lower-level programming to get extra performance.
Some preconceived notions forced upon you by C, off the top of my head:
- problems should be solved by describing a linear sequence of steps (as opposed to logic/declarative programming)
- a variable can have different values at different times in the execution of a program (in contrast to standard mathematical conventions)
- a function can return different results when called multiple times with the same arguments (again, in contrast to the standard mathematical meaning of the term)
- there is random access storage of information (with constant time access and update)
Linear sequences of steps processing data arrayed in some linear fashion or others is what computers do. It is certainly what a single core does.
So you would rather have someone else write a C program for you that abstracts it away and calls it a new way to program? That's k, just know that you'll still have those pesky linear steps under the hood. You know, at some point the neat source you write actually has to get converted into stuff CPU can make the slightest bit of sense out of.
Of course it's nice to try to "get the computer think like the programmer instead of the other way around" (kind of the motivation for the inventor of the compiler IIRC, in times when people really had to "speak binary" to the computer), but it also kinda sucks when people completely loose track of the machine they're programming, and think their abstraction layers du jour grow on trees or something.
a variable can have different values at different times in the execution of a program (in contrast to standard mathematical conventions)
Your problem is nomenclature? Why not simply declare constant variables where you need them and move on? And are you really trying to twist C giving you the choice into "forcing preconceived notions" on programmers? That is hilarious, I will give you that much.
a function can return different results when called multiple times with the same arguments (again, in contrast to the standard mathematical meaning of the term)
"Function" can also mean a lot of people coming together for a wedding or something. I think that's why you would call them "C function" if you wanted to be precise.
there is random access storage of information (with constant time access and update)
Again, that's just how "the world" works. But C hardly came up with that, which is why all languages have it.. yes, all of them. Some abstract it away from you, sure, but they still have it. So you pay overhead and control "tax" in return for convenience and and expressiveness; that's not a bad thing per se, often it's the sane and productive choice, but to me dissing C is just shitting where you eat. The only reasons I can imagine for it are jealousy or ignorance.
No, it's what some computers do. It's almost certainly not what the computer you are using currently does. It's quite possible it's not what any computer you've ever used does.
> So you would rather ...
I'm not expressing a preference. If you think I was, you've misunderstood my comment. I'm making observations, not judgements. I'm not anti-C, it's a fine language for many things; however I do think that the articles author is not being as even-handed as he claims when it comes to some of the short-comings of C.
> Your problem is nomenclature?
Again, I'm not making a judgement. C exists in a paradigm where writing
x = 3
x = 4
makes sense. In other paradigms it would be logically inconsistent.>>there is random access storage of information (with constant time access and update)
>Again, that's just how "the world" works.
That's absolutely not how "the world" works. Again, you've probably never even used a computer where it was true.
> dissing C is just shitting where you eat. The only reasons I can imagine for it are jealousy or ignorance.
I don't think I've made any statement anywhere in this discussion that's "dissing C".
Nope, not forced on you, because plenty of systems implemented in C define models in which none of what you mentioned is true. For example, the Haskell runtime is implemented in C. That's the whole point of what I'm saying. A stack with C at the bottom allows Haskell to exist with good performance even though the hardware/OS were not designed with Haskell in mind. The reverse is not true.
Why do you suppose that no serious VMs or language runtimes are written in Haskell (or other functional languages)?
You realize C is not at the bottom of the stack, right?
> Why do you suppose that no serious VMs or language runtimes are written in Haskell (or other functional languages)?
Because Lisp Machines didn't win.
> plenty of systems implemented in C define models in which none of what you mentioned is true
True, but that's the whole point of abstraction. C, in turn, gets rid of some of the "preconceived notions" of the layers under it.
... except for a type system based on the memory model of a machine which strongly resembles the PDP-11, a compilation strategy built for machines with less RAM than my car fob, and optimization possibilities limited by aliasing, plus everything kscaldef mentioned.
I'm interested in hearing about alternative memory models that are an improvement; every one I hear about is specific to some higher-level language or programming paradigm. Baking high-level language concepts into hardware is basically asking for stagnation.
> a compilation strategy built for machines with less RAM than my car fob
C is adapting (see: http://www.infoq.com/news/2012/11/llvm-modules)
> optimization possibilities limited by aliasing
"restrict" exists, and while it's not perfect, I have not seen anything that is a Pareto improvement over it. In other words, every alternative that avoids aliasing problems (that I have seen) makes other trade-offs that make it a worse choice overall (including FORTRAN, which I am sure you will mention).
Intel 80286 introduced segmented protected mode where you had the option of placing each of programs objects (struct, array, string, even a single variable, if necessary!) into its own segment described by privilege access level (0-3, RO or RW) and length. So you had hardware-based array length checking. Access an out-of-bounds index, BOOM - segfault!
This is actually not incompatible with C's memory model (it requires that only individual objects be stored in contiguous memory blocks), but is incompatible with how most C programs were written at the time so it never caught on.
Also, you had to distinguish between "near" and "far" pointers, there were few segment registers, etc. But had Intel developed segmentation further, and had C programmers adapted, we could have ended up in the world where you could run programs with performance of C and safety of Java.
Case in point: Whenever you're doing signed arithmetic, and it overflows, you're in the land of undefined behaviour. (See here for an example of how this can bite you: http://thiemonagel.de/2010/01/signed-integer-overflow/)
Another case in point: type-punning with through pointer casting is also UB. [Going through union is legal though.]
I'm pretty sure the author hasn't written a line of ANSI-C compliant code in his life, otherwise he'd never write something like this.
There are definitely annoyances and issues, but they are known and can be taken into account with much less hassle than attempting to grok a Java project that requires you to traverse into the basest-level of classes like BusinessObject2013SingletonDispatcherFactoryFactory every time something needs to be debugged or fixed.
It doesn't mean you should use C for your Web 2.0 startup, but his point is well taken. I heard someone 'round these parts once acknowledge that the modern equivalent of spaghetti code (i.e., code that intractably descends through hundreds of code paths with gotos, etc.) is OO hell, i.e., code with huge dependency stacks and equally intractable and unjustifiable inheritance models, where you have to descend into all kinds of classes and special cases to make a meaningful change.
>I'm pretty sure the author hasn't written a line of ANSI-C compliant code in his life, otherwise he'd never write something like this.
Damien Katz is actually fairly accomplished, and it definitely sounds like he's written multiple lines of C to me.
No, it's not the language features which make a mess. It's people lacking judgement and common sense. (Like, trying to apply patterns everywhere. Been domain-specific [crypto] consultant on such a project and watched it smash the schedule by more than 2x. It wasn't the language [Java], it were stupid people.)
> sounds like he's written multiple lines of C to me
I don't contend that he's written a lot of C. I DO, however, contend that he's written some ANSI C. If you're writing ANSI C, you have to account for AT LEAST all of the following behaviors:
https://www.securecoding.cert.org/confluence/display/seccode... https://www.securecoding.cert.org/confluence/display/seccode...
For example, if f is some function, then in the sequence
int x = 0;
f(x++, x++);
the call to f is undefined behavior because x is modified twice without an intervening sequence point. Anybody claiming that such language is "high-level" is a moron, regardless of their "accomplishments".My thoughts in more depth at http://blog.lukego.com/blog/2012/09/25/lukes-highly-opiniona...
When you write something to be fast in C, you know why
it's fast, and it doesn't degrade significantly with
different compilers or environments the way different
VMs will, the way GC settings can radically affect
performance and pauses, or the way interaction of one
piece of code in an application will totally change
the garbage collection profile for the rest.
The implementation of malloc & free that your C implementation uses significantly impacts performance (both time and space) just like the choice of GC implementation in other languages. It is not uncommon for memory fragmentation to be a serious problem for large or long-running C programs, and at the point that you have to start worrying about that and working around it, you've broken the abstraction in just the same way that the author complains about for Java, Erlang, Haskell, etc.Also, as others have pointed out, performance can also depend significantly on how well C's machine model maps to the actual machine architecture you're running on.
I wonder if this gentlemen has tried Go? If he is a big C fan, Go might be a great choice for the other 90%. Not only is Go a safer version of C with lots of great modern features, it integrates very well with C via cGo.
If memory usage and speed are your preeminent concerns, C is certainly a force to be reckoned with: http://benchmarksgame.alioth.debian.org/u64q/which-programs-...
If you are working in C and think you might like closures and a different concurrency model than pthreads, then you should look into clang+libBlocksRuntime+libdispatch. That gives you the blocks(closures) known to OS X and iOS programmers and a pretty spiffy queue based concurrency model. I'm never going back to pthreads. You can't make me.
Slightly sadly, I haven't seen a distribution shipping a modern version of libdispatch. There is one in github, but it may or may not have a problem in its read/write support. I use the old version that comes in my distribution.
Interactive languages blow anything with a Build-Run cycle away. "Faster" doesn't matter.
Having a Build cycle is not one of C's advantages. It is a trade off (and a good one, if you care about speed of execution vs speed of development).
Dropping down to C has taken an attitude adjustement, and a willingness to drop certain kinds of features, but it's really been quite refreshing.
Oh, but this time it's different, this time it's the real thing?
That's nothing to do with C. It's because Damien worked on CouchDB first, and learned a lot from that. If I were to go and rewrite our current system in Java or Scala, I'd also be able to predict where performance, and other, issues would crop up, simply because I've already encountered a number of them before.
Another way to look at this is that all languages which offer poor abstractions force you to write more code, by definition. Up front you will have to write much more code, but when the inevitable bug comes up, you will have the luxury of debugging code you authored. For some individuals and teams, this trade-off is a sensible one.
There are instances where writing it yourself is the better option, but more often than not you will want to offload that burden onto a library that deals with the details so you can focus on doing what's important to your system/business.
[1] http://www.codinghorror.com/blog/2008/03/the-first-rule-of-p... [2] http://www.codeofhonor.com/blog/whose-bug-is-this-anyway
Arguably, one of the most beautiful C-code bases you can get hold off.
Saying C is always effective without further qualification is like saying that high speed racing cars are always effective. You need vans, trucks, bulldozers, etc, etc.
Then there is the question of what is really meant by "effectiveness". Is the code execution speed, maintainability, collaboration, compile-execute cycle, extensibility, etc?
As always, it depends on what you want to do. In many cases C is the most logical choice. But in other case Java or other languages get the job done more "effectively".
Anybody who is limiting him/herself to a single language to "rule them all" is certainly not effective.
Edit: Usual spelling mistakes.
So true. C++ is designed by someone who is a moderately smart but not a great engineer. There are too many details without much benefit, and you are encouraged to hide things in obfuscated manners, rather than doing straightforward programming.
Faster Build-Run-Debug Cycles [...] C has the fastest development interactivity of any mainstream statically typed language.
I could understand someone praising Go for this, because the language designers specifically targeted fast builds for example by making the syntax easy to parse efficiently, hence achieving good build times while keeping the language relatively high level, but C simply does little for the programmer and hence the builds are faster than in Java or Haskell. You could maybe admire the decades of work put into C compilers, but not C the language itself for it.
Also, if you criticize high-level languages for being far removed from the computer it would be fair to point out that wider understood "development interactivity" of C compared to something like Smalltalk is rather bad. Consider also that this removal from the computer could be as much an argument against our current computer architecture as it is an argument against high-level programming languages. That we have invested decades into a technology and can't easily switch to a different one doesn't mean we should stay uncritical about its weaknesses.
Ubiquitous Debuggers and Useful Crash Dumps
I suspect this is a sign of disappointment with Erlang, where debugging seems to be a complete mess, the last time I was doing some development in it I had to fire up some really weird looking debugger and run the program under it just to get something reassembling a stack trace with the filename and line number for the error I got in the program. But you do have lots of debuggers and crash dumps in the JVM for example and I don't think you all that often need to examine the level below the JVM when debugging JVM-based programs. It's somewhat funny to praise C for being convenient in interactions with other C code.
Contrast this to OO languages where codebases tend to evolve massive interdependent interfaces of complex types, where the arguments and return types are more complex types and the complexity is fractal, each type is a class defined in terms of methods with arguments and return types or more complex return types.
I don't know what this is even supposed to mean. From what I know most large scale C programs end up desperately trying to emulate some of the features of higher-level languages to create more strict module boundaries and prevent implementation details from breaking the library interfaces.
As a 20+ years C++ programmer, I sadly found there seems no scenarios that C++ can play very well. Compared to C, C++ projects are much harder to maintain. Whenever C++ should be used, C is always a better option.
Wouldn't that imply that a variable of one type could be coerced into another type?
I would say C is strong typed...
int i;
float f = *(float*)&i;
I'm not saying you should do this, but you can.Or to use an example the author didn't regret:
struct foo {
int a;
int b;
int c;
}__attribute__((packed));
void print(foo* f) {
int *p = f;
int i;
for (i=0; i<sizeof(foo)/sizeof(int); i++) {
printf("%d,",p[i]);
}
} struct meta_obj {
meta_obj_type *next; // next object in our list
mark_type mark;
size_t size;
gc_type_def type_def;
uint8_t obj[]; // contained object
};
Or another (contrived) example: struct obj_type {
obj_type_enum type;
};
struct string_obj_type {
obj_type_enum type;
char *c;
};
You start with a collection of obj_type pointers and cast them to the appropriate pointer type when you have identified the actual contained struct. Useful if you need to have a heterogeneous list of things.Yup! It's quite common to cast things from a void * to a more specific one. You do it every time you call malloc.
I finally decided to get a deeper knowledge of C, something I've been saying I "should do" for years. I'm learning it via Zed Shaw's Learn C The Hard Way and I'm very impressed by the language. It does what it does very well. I wouldn't use it for a complex web app, but it's a fine language for things that are small but in which quality (which includes performance) is extremely important.
I'm growing to like C a lot, and I think people who don't bother to learn it are short-changing themselves in a major way. That said, there are a lot of great languages out there that are better-suited to high-level projects... so long as the concerns remain high-level.
For most of my time, I focused more on user experience (syntax, type system, workflow) and its effects on development culture. Watching language choices make or break companies made me very opinionated. That said, as I get older, I'm finding it harder to call specific languages "good" or "bad". They all have their niches. Enterprise Java is horrible, but that's not James Gosling's fault.
What's its niche? C's major win is the ability to explicitly manage (and, thereby, reason about) memory. Garbage collection is great but I tend to associate it with high-level languages like Python, Haskell and Clojure.
I'm sure there is a niche for GC'd mid-level languages (e.g. Go) but I'm not yet experienced with them enough to know what it is.
For language beauty, the ones with simple syntax (e.g. Lisps, Forth, q) win. However, for a large production system, I'd be more inclined to use something with static typing.
Static typing falls down in a different way with large systems-- compile speed-- but if the thing's not being changed on a regular basis, that's not a huge issue.
You can still allocate a gigantic primitive array (say of Java 32-bits integers) and mess with it, including doing bit-trickery, etc. and that is amazingly fast.
When people want the uttermost speed in Java, they dodge objects as much as they can to prevent too much GC'ing.
For example that is how the people behind the amazing LMAX disruptor "pattern" (hardly a "pattern" in the OO sense) manage to handle, on a single thread, to process about 12 millions events... Per second. In Java.
"Thankfully" Java still allows to create a gigantic primitive array and to directly mess inside that array.