LWN.net Logo

Why learn C? (O'Reilly Radar)

O'Reilly Radar has published an interview with author David Griffiths on the continued relevance of teaching C. The main interview in in video form, with text excerpts highlighting specific points, such as "For example, it teaches how memory works in a more profound way (a concept systems programmers will likely already know, though new programmers in specialized fields might not)" and "It's an important, foundational language that requires you to understand the full stack of the technology."
(Log in to post comments)

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 18:53 UTC (Thu) by felixfix (subscriber, #242) [Link]

I have often thought that for programmers, the best first language is assembler / machine language, not because that itself will ever be much used again, but because it teaches the most fundamental constraints on computers, like instructions have variable timing and space requirements, and there are tradeoffs between the two.

I know way too many higher level programmers, including just plain C, who think counting lines of code is a good indication of the speed and size of code. They utterly ignore sub calls and complex multi-level data structures.

Then you get to the object oriented crowd who additionally cannot see any disadvantage to anything object oriented. They cannot articulate any tradeoffs between speed of development vs speed of execution.

I realize good design has little to do with counting cycles and bytes, but there are simply too many programmers who have no comprehension of anything below lines of code. Good design has a practical side too. It's more than just throwing cycles and memory at a problem.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 20:36 UTC (Thu) by wahern (subscriber, #37304) [Link]

They cannot articulate any tradeoffs between speed of development vs speed of execution.

There's no tradeoff to articulate. The stricter the OOP model, the more both development and execution costs increase. Is this not common wisdom, yet? ;)

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 17:27 UTC (Fri) by iabervon (subscriber, #722) [Link]

On the other hand, counting cycles only makes sense for some embedded architectures these days. On x86_64, your speed is going to be most affected by cache misses and pipeline stalls, neither of which you can determine by looking at the assembly. For that matter, you don't even really know how many cycles any particular instruction will take or which instructions may overlap; when you're writing the code, the processors that will end up running it may not have even been selected yet, so you can't know their microarchitecture.

In any case, I think that learning assembly is a terrible thing to do first, but it's a good thing to do before learning algorithms. Assembly would be a good first language for people who are somehow already programmers, but its better for making someone a programmer to pick something that lets you do something practical with only a small amount of effort.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 19:01 UTC (Thu) by cmorgan (guest, #71980) [Link]

One downside is that other modern languages are much more efficient and natural to program with. One upside is that at least when they go from C to one of those modern languages they'll be more aware and appreciative of what is going on behind the scenes.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 19:39 UTC (Thu) by HenrikH (guest, #31152) [Link]

That modern languages are way more efficient than C is a mantra that keeps getting repeating over and over but is it really true? I have worked on many different projects and regardless of it beeing gui, no-gui, web site, web services etc I have yet to encounter a situation where C gave my a disadvantage against my colleagues using Java, C# or PHP.

My belief is that what the new programmers see as the main advantage in the modern languages is the framework. But as a experienced C programmer I have a vast framework in the form of shared libraries, both my own but mostly the vast array of libraries in a modern Linux distribution.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 19:49 UTC (Thu) by Otus (guest, #67685) [Link]

I've yet to see a GUI toolkit/interface that wasn't a pain to use in C.

Other than that, I definitely agree.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 21:22 UTC (Thu) by dskoll (subscriber, #1630) [Link]

I've yet to see a GUI toolkit/interface that wasn't a pain to use in C.

Sadly, Tcl and Tk are no longer in vogue, but at the turn of the millennium I developed a couple of large C++ (ok, not C, but close) projects that embedded Tcl and used Tk as the toolkit.

Tcl proved to be a terrific embeddable language; its C API is simply wonderful compared to some monstrosities such as embedded Perl. Whipping up GUIs in Tcl/Tk is pure joy.

I don't think we should be afraid to use C where it's appropriate and non-C where it isn't.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 21:43 UTC (Thu) by dashesy (subscriber, #74652) [Link]

If C++ is in the list, I think Qt beats any other GUI toolkit/interface. I think the OP is talking about plain C.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 22:44 UTC (Thu) by wahern (subscriber, #37304) [Link]

Tk is written in Tcl, but the C API is a first class citizen, which is how you end up with things like Perl/Tk. And Tk is widely considered a breeze to work with, and (correct me if I'm wrong) may have been one of the first toolkits to handle widget nesting, placement, and resizing automagically.

So, it's a GUI toolkit for C which may be the easiest to use of all of them, even accounting for Qt, Silverlight, etc.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 0:14 UTC (Fri) by dskoll (subscriber, #1630) [Link]

...handle widget nesting, placement, and resizing automagically

That's correct. Tk's geometry managers (the packer, the placer and the gridder) are still better than any other toolkit geometry managers I've seen.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 8:19 UTC (Fri) by rwst (guest, #84121) [Link]

And when I recently had a look at Qt I specifically sought
such a placement function, and was quite disappointed that
it wasn't included.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 12:14 UTC (Fri) by richmoore (subscriber, #53133) [Link]

Qt has quite a decent set of layout managers, which one were you missing?

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 0:13 UTC (Fri) by dskoll (subscriber, #1630) [Link]

Tk is plain C. I just happened to use it from a C++ project, but it's equally useful in C projects.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 19:43 UTC (Mon) by landley (guest, #6789) [Link]

C++ is not C. Saying "C++ contains C, therefore C++ is a good language" is like saying "a mud pie contains water, therefore mud pies are a good beverage".

C is in a sweet spot of minimal abstraction: enough to get portability between arm and x86 and such. Not enough to obscure what the hardware is actually doing, but enough that the "how" can get washed through somebody else's optimizer. (The old joke "C combines the flexibility of assembly language with the power of assembly language" is funny because it's true.) C lets you program close to the bare metal without having to care whether a branch delay slot is allowed to cross a cache line boundary this week, or starting all over every time somebody invents a new architecture (of which linux supports dozens: arm for phones, x86 for desktops, ppc for game consoles, mips for routers, sparc and itanic for bureaucrats, ...).

The _other_ sweet spot is up with ruby and python and lua (oh my!), scripting languages which provide thick but reliable abstractions so you can program to those abstractions without knowing how it was implementated. These languages replace pointers with references and on top of that build dynamic memory (garbage collection), and dynamic typing (duck typing), and combine them to put flexible container types into the base language. You don't have to care whether a python dictionary is a hash table or a tree under the covers; it doesn't matter, it just _works_. Scripting languages are so dynamic they do away with compilation entirely and set the executable bit on the source code: maybe they do a just-in-time bytecode compiler pass under the covers, but you can ignore it.

Between "dynamic everything with thick, opaque, reliable abstraction" and "static everything with as little abstraction as possible", you have a middle ground of "mixed static and dynamic with leaky abstractions". The worst of both worlds. Languages like C++ provide all sorts of abstractions like templates and std string types, but the implementation details intrude into the language so you have to understand how they're _implemented_ to use or debug any of them.

There's a difference between having to understand how a language feature is _used_ (ala C code) and regularly having to reverse engineer your compiler and standard template library to debug your problem (C++). In C++ you learn piles of caveats to the base language, "don't throw an exception from a constructor", "don't think you can avoid having to manually initialize every data member in your constructor with memset(this, 0, sizeof(*this));", and of course how a piece of data can live on the stack, on the heap, in the globals, in the process environment space, or be mmaped, each with its own lifetime rules. Good luck if you mix two of them in the same container through an abstraction that did an unexpected call by reference instead of call by value. For exatra fun: templates are turing complete _at_compile_time_, which means there's no way to prove a C++ compilation using templates will ever finish.

C++ never got rid of pointers, and then attempted to build elaborate abstractions on top of them. Since pointers inherently cut through abstraction (it's what they're _for_), these abstractions leak. Making the abstractions _thicker_ is painting over dry rot with more and more coats. The C++ guys keep acting like they can escape a poor foundation by building higher, that adding enough stories will render the sand underneath the whole thing irrelevant. With each new standard the language gets larger the problems with it get harder to understand and explain, which is considered progress.

C is a local peak. Scripting languages are a local peak. C++ is in the valley of suck between the peaks. Sure you can strap rocket engines to a turtle and make it work; people wrote and deployed millions of lines of Cobol and Ada code too. That doesn't make it a scalable, robust, or efficient language.

Every time a discussion of C wanders blithely into C++ as if it's the same thing, somebody doesn't know what they're talking about. And _that_ is what the above interview was about. We are teaching C++ as if that's a replacement for teaching C. It is not.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 21:52 UTC (Mon) by nix (subscriber, #2304) [Link]

As someone who likes C++ for its expressiveness and power, and who wrote C++ before he wrote C, and OO code before he wrote procedural code, I tried very hard to disagree with you... but...

... dammit, you're right. And I don't just say that because I'm working in the very small subset of code that pretty much *must* be implemented in C for reasons unrelated to efficiency. (You're also working in that subset, which is probably why we agree on this point.)

You *can* write C++ that avoids the traps you describe (and with C++11, it gets easier) -- but you do need to be an expert to do it, everyone who works on the project needs to be an expert too, and you need to avoid almost every piece of example code that exists out there on the Internet as well. Which means that hardly anyone writes good C++. (By comparison, a far higher percentage of C developers can write good C, though the percentage is still small and it still takes the usual time for any human field of roughly ten years to become anything close to expert.)

Why learn C? (O'Reilly Radar)

Posted Jul 3, 2012 15:10 UTC (Tue) by dashesy (subscriber, #74652) [Link]

everyone who works on the project needs to be an expert too
And everyone who will be working on the project! Forever without a gap, if there is one person in between that does not know most of those traps, it soon becomes unreadable and hard to understand and debug (the worst that can happen to a project). Specially the corner cases (that C++11 promises to solve with first class language idioms) tend to accumulate more cruft. I really appreciate that kernel, and what landley is doing is using C. Whenever code beauty matters (and not time to market), if code does not work it should be replaced, not sub-classed.

Why learn C? (O'Reilly Radar)

Posted Jul 4, 2012 12:13 UTC (Wed) by jwakely (subscriber, #60262) [Link]

> In C++ you learn piles of caveats to the base language, "don't throw an exception from a constructor",

Nonsense.

> there's no way to prove a C++ compilation using templates will ever finish

Erm, except to maybe try compiling it. Templates are Turing complete, but in practice compilers have limits on how many levels of instantiations they'll handle and rapidly run out of memory (and crash) if you do something stupid/crazy.

And so what? Is the fact that there's no way to prove a C program will ever finish a practical problem? If not, why is the Turing completeness of templates a practical problem?

Why learn C? (O'Reilly Radar)

Posted Jul 4, 2012 12:39 UTC (Wed) by dgm (subscriber, #49227) [Link]

>> In C++ you learn piles of caveats to the base language, "don't throw an exception from a constructor",

>Nonsense.

Maybe just misinformed. In fact, exceptions are the only way to propagate errors in constructors, you cannot return an error code. But I guess what he really meant was "destructor".

Why learn C? (O'Reilly Radar)

Posted Jul 10, 2012 4:11 UTC (Tue) by smitty_one_each (subscriber, #28989) [Link]

"For exatra fun: templates are turing complete _at_compile_time_, which means there's no way to prove a C++ compilation using templates will ever finish."

I mostly think you're making a good, substantial case in this article, but the hyperbole blunts the argument.
How much theorem proving have you _ever_ done with code, irrespective of language?

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 10:19 UTC (Fri) by Otus (guest, #67685) [Link]

I haven't used tcl/tk, so apparently I've missed the one that works.

Trying to read the source of any "modern" GUI app written in C is painful.

(Not that those written in other languages are necessarily much better.)

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:48 UTC (Fri) by man_ls (subscriber, #15091) [Link]

The source of a well structured, OOCSS web page can be surprisingly nice to read. Even adding some javascript it remains good enough to understand on the fly. That is perhaps why web applications are taking the world by storm.

Speaking of javascript, I think that C is good to learn, object oriented is fine, but any developer that doesn't know a functional language is missing out a lot (and doesn't know what is missing). I come from a Java background and I know a bunch of people like that.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 23:24 UTC (Thu) by nix (subscriber, #2304) [Link]

I wouldn't describe Java, C# or PHP as modern languages in that sense. LuaJIT is at least as fast as compiled C, and Lua as a language knocks the socks off C. (The same is true of a number of other languages.)

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:05 UTC (Fri) by tjc (subscriber, #137) [Link]

> Lua as a language knocks the socks off C.

C doesn't have socks, so I think you must be mistaken.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 5:22 UTC (Sat) by dirtyepic (subscriber, #30178) [Link]

Socks were added in C11. Unfortunately they were almost immediately knocked off again, which explains why they can't be found in the spec.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 17:25 UTC (Sat) by tjc (subscriber, #137) [Link]

Yes, and all those C11 socks start with an underscore (_Alignas, _Alignof, _Atomic, &c.) like some of their C99 predecessors. I realize there are reasons for this, but it's turning C into kind of an ugly language.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 5:04 UTC (Sun) by wahern (subscriber, #37304) [Link]

Most of those have non-prefixed versions which you can get by including a header. For example _Bool has <stdbool.h>, which does #define bool _Bool. For _Alignof include <stdalign.h> and get alignof. <stdatomic.h> does the same for many other types.

In C anything that starts with an underscore followed by a capital letter, or anything which begins with two underscores, is reserved for future language extensions. That way, new extensions won't break existing code. If you want the intuitive names, include the headers.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 1:23 UTC (Fri) by HelloWorld (guest, #56129) [Link]

> That modern languages are way more efficient than C is a mantra that keeps getting repeating over and over but is it really true?
Yes it is.

> I have worked on many different projects and regardless of it beeing gui, no-gui, web site, web services etc I have yet to encounter a situation where C gave my a disadvantage against my colleagues using Java, C# or PHP.
You're just denying reality here. C lacks tons of features that make everyday things much easier to write and debug and less error prone, such as automatic memory management, bounds checking, a sane type system, a module system, exception handling, closures etc.. These things were invented for a reason.

> My belief is that what the new programmers see as the main advantage in the modern languages is the framework. But as a experienced C programmer I have a vast framework in the form of shared libraries, both my own but mostly the vast array of libraries in a modern Linux distribution.
It's hard to implement good libraries if you're hampered by a language like C. It's pretty much impossible to do string handling in a sane way in C due to the lack of automatic memory management. You can't write a sane (generic, type-safe, fast, no preprocessor nonsense) container library in C. Arbitrary-precision arithmetic is horrible due to the lack of operator overloading.

So sorry, but you're utterly wrong. C is a millstone around the developers' necks for almost every project nowadays.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 7:09 UTC (Fri) by kleptog (subscriber, #1183) [Link]

You're just denying reality here. C lacks tons of features that make everyday things much easier to write and debug and less error prone, such as automatic memory management, bounds checking, a sane type system, a module system, exception handling, closures etc.. These things were invented for a reason.
I think that's kind of the point. All those things you refer to simply do not exist at a hardware level. If your goal is to teach people how computers actually work then you need to use a language whose model resembles that of the underlying machine, and C does that.

FWIW, I think it would be instructive for new programmers to think about, for example, how you would actually implement things like exception handling in C, just so they appreciate what is being done for them. Many of the things you describe are decidedly non-trivial.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 7:51 UTC (Fri) by HelloWorld (guest, #56129) [Link]

> I think that's kind of the point. All those things you refer to simply do not exist at a hardware level. If your goal is to teach people how computers actually work then you need to use a language whose model resembles that of the underlying machine, and C does that.
My comment was a response to HenrikH's comment where he questioned the productivity advantages of modern high-level languages. I didn't mean to debate the utility of C as a teaching tool.

Besides, I don't think your comment is very convincing either. The problem is that C sucks even as a low-level language. There's no reason for not having a sane module or type system in a low-level language, not to mention the various C antifeatures like the stupid syntax and the preprocessor.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 8:42 UTC (Fri) by dgm (subscriber, #49227) [Link]

A list of features is not very convincing, either. Real World measurements, _that_ would be convincing! Show me measurements of effort put into creating real applications in different languages and we can start to talk.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:10 UTC (Fri) by tjc (subscriber, #137) [Link]

I know I shouldn't be feeding trolls, but why do you think C's syntax is "stupid?" The only thing that really stands out to me as not-so-hot is the prefix pointer declarator.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 23:38 UTC (Fri) by HelloWorld (guest, #56129) [Link]

I don't know why I'm even responding to this, given that you're calling me a troll without any justification.

Anyway, the main problem with C is its declaration syntax. Let's take a declaration like

void (*signal(int, void(*)(int)))(int);
This is ugly for two reasons. One is that parenthesis are required to distinguish void *(int) from void(*)(int). The other is that the tokens that describe the function's return type are split up: the void(* in the beginning and the )(int) in the end belong together, which is harder to figure out than necessary. Using a postfix pointer declarator fixes the first problem but not the second:
void signal(int, void*(int))*(int);
This is fixable by using another syntax for simple declarations: i int; instead of int i;. That would lead to a declaration like this:
signal(int, *(int)void) *(int) void
This also offers the advantage that the name being declared is always at the beginning of the line. It also makes preprocessor macros that involve declarations easier to write.

Another problem with the C syntax is that in function parameter declarations, foo[] means the same as foo*, while everywhere else it doesn't. People keep confusing arrays and pointer due to this (though the implicit conversion from foo[] to foo* also promotes this).

I also find it ugly that while both :? and if/else exist, there is only a switch statement and not a switch expression.

And just to be clear: the C syntax is actually not the greatest of C's problems. The lack of sane type and module systems is a much greater burden.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 17:48 UTC (Sat) by tjc (subscriber, #137) [Link]

> signal(int, *(int)void) *(int) void

That's going to be hard to parse. The lexer is going to return a token with the value "signal", but the parser is going to be sitting at the top level without any context in which to evaluate it. If it's not a reserved word then it must be an identifier, but nothing else is known about it without peeking further ahead into the input stream.

Something like this would be more practical:

func signal(int, *(int)void) *(int)void

I personally don't mind that C (and C-like languages) anchor declarations with the type. It's still a left-to-right parse, with the single exception of the type. The "var|func ... <complete return type>" syntax is probably better, but I've been looking at "<type> ..." for so long that it seems natural to me. It also allows you to do things like this:

int i, j;

As far as the foo * vs. foo[] thing, that's not really a syntax problem, it's a semantic problem, given that arrays decay to a pointer to the first element in most (but not all; e.g. sizeof(foo)) cases. I agree that that could be changed, and it would be better in most cases. I usually write array parameters as foo *, just because that's what they really are inside the function.

I'm not aware of the difference between a switch statement and a switch expression, so I can't comment on that. I guess I better start "googling."

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 11:15 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> That's going to be hard to parse. The lexer is going to return a token with the value "signal", but the parser is going to be sitting at the top level without any context in which to evaluate it. If it's not a reserved word then it must be an identifier, but nothing else is known about it without peeking further ahead into the input stream.
I fail to see how conventional C syntax is any better. In a declaration such as foo *bar;, you have exactly the same situation, and to be honest, I don't even see why it's supposed to be a problem.

The only problem I see with this syntax is that it's ambiguous: there's no way to know whether foo(bar)*baz; is a declaration or a statement without looking at the preceding declarations in order to find out whether bar and baz are variables or typedef-names. Alas, conventional C syntax has the same problem in declarations such as the above-mentioned foo *bar;.

It's also fairly easy to disambiguate it using a syntax such as
foo: (bar)*baz;
That would clash with the goto label syntax, as foo: bar; is valid C code. However, this is not a problem: bar; is a statement without effect, so there's no point in writing code like that, therefore a line like that should be parsed as a declaration.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 22:30 UTC (Sun) by tjc (subscriber, #137) [Link]

I can't think of a situation in C where an expression that begins with a type specifier is anything other than a declaration. I could be overlooking something, but I'm looking at the grammar in appendix A13 of K&R, and I don't see anything.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 22:49 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> I can't think of a situation in C where an expression that begins with a type specifier is anything other than a declaration.
Uh, so? In a declaration like foo *bar, you still have to know whether foo is a typedef or a variable name in order to know whether it's a multiplication or a declaration.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 23:02 UTC (Sun) by tjc (subscriber, #137) [Link]

The compiler has this information available to it in the symbol table.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 23:20 UTC (Sun) by HelloWorld (guest, #56129) [Link]

I know, this is the well-known lexer hack. I still don't see how the syntax I've proposed is supposed to be any more problematic than conventional C syntax.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 20:36 UTC (Mon) by tjc (subscriber, #137) [Link]

The type specifier in a C declaration acts as a surrogate for the missing 'var' or 'func' keyword, which makes it possible for the parser to recognize the declaration without requesting a lot of extra tokens from the lexer.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 21:23 UTC (Mon) by HelloWorld (guest, #56129) [Link]

I think that this is only a problem when using top-down parsers. A bottom-up parser should handle this situation easily.

Why learn C? (O'Reilly Radar)

Posted Jul 3, 2012 15:46 UTC (Tue) by tjc (subscriber, #137) [Link]

Yes, it could be made to work, but it would have to be a backtracking parser, and it would probably be slow. Most bottom-up parsers (such as those produced by bison) are LALR(1), which only has one token look-ahead.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 22:59 UTC (Sun) by tjc (subscriber, #137) [Link]

I wish there were some way to edit posts after posting so that my mistakes are not permanently recorded for posterity. :)

I should have said, "I can't think of a situation in C where a statement that begins with a type specifier...."

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 9:30 UTC (Mon) by nix (subscriber, #2304) [Link]

Quite, thus ruling out sizeof().

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 11:28 UTC (Fri) by adobriyan (guest, #30858) [Link]

> Many of the things you describe are decidedly non-trivial.

Seeing small, unknown C project called Linux the kernel from inside,
I agree that C sucks even as low-level language.

Multiple return values.
Less stupid preprocessor, more compile-time evaluation!.
Precise alignment and offsets of structure fields (constant and "modulo by" constraines).
Less "undefined behaviour" beartraps!

All of this could be added without sacrificing "close to machine" property some love so very much.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 2:55 UTC (Sun) by vonbrand (subscriber, #4458) [Link]

Multiple return values.

You can return a struct... and multiple return values would require handling multiple values all over the place (asignments, comparisons, ...). Nifty, but definitely not "low level." C is OK as is here.

Less stupid preprocessor, more compile-time evaluation!

The preprocessor is decidedly not stellar. Better use m4(1) perhaps? Or just chuck it altogether (given const and enums, and inline functions, its use is mostly for #include nowadays). Plus current compilers are quite smart at getting rid of useless code and constant folding, so "compile time evaluation" is given much more than you perhaps realize.

Precise alignment and offsets of structure fields (constant and "modulo by" constraines).

Sorry, but if you want a low-level, efficient language, you have to give the compiler leeway to accomodate the architecture's quirks.

Less "undefined behaviour" beartraps!

Ditto.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 12:22 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> You can return a struct... and multiple return values would require handling multiple values all over the place (asignments, comparisons, ...). Nifty, but definitely not "low level." C is OK as is here.
This has nothing to do with high-level-ness. It doesn't require dynamic memory allocation or other fancy run-time implementation techniques and you don't lose any control over your code.

> Sorry, but if you want a low-level, efficient language, you have to give the compiler leeway to accomodate the architecture's quirks.
If one doesn't specify the data structure layout, the compiler would still be able to decide by himself what to do.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 20:42 UTC (Sun) by kleptog (subscriber, #1183) [Link]

>> You can return a struct... and multiple return values would require handling multiple values all over the place (asignments, comparisons, ...). Nifty, but definitely not "low level." C is OK as is here.

> This has nothing to do with high-level-ness. It doesn't require dynamic memory allocation or other fancy run-time implementation techniques and you don't lose any control over your code.

Returning multiple values is something that would require ABI support. Only values in the registers can be returned because the callee stack frame vanishes at return. Returning structs is already something poorly supported, because if it doesn't fit in registers, where do you store it then? The reason C++ can do it is because new/delete are part of the language, as are (copy) constructors. (I believe it's done with hidden extra parameters).

It would also require making a list a first class object in the language.
You could possibly come up with an ABI that supported returning multiple values in a way that was an improvement over what you can do already and make it work on all the myriad of processors in existence, but I just don't see the demand.

I think C's simple, predictable ABI is key to its continuing popularity. Any language, including dynamic languages, can call into a C library. If you have a C++ library it's already much harder, and calling from (for example) a python script into a perl library is essentially impossible.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 20:56 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> Returning multiple values is something that would require ABI support.
Uh, so what?

> Only values in the registers can be returned because the callee stack frame vanishes at return. Returning structs is already something poorly supported, because if it doesn't fit in registers, where do you store it then?
On the stack of course. Also, returning structs isn't "poortly supported" at all, it works just fine.

> The reason C++ can do it is because new/delete are part of the language,
That's simply nonsense.

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 22:24 UTC (Sun) by nix (subscriber, #2304) [Link]

To be fair, returning structures was poorly supported once. Of course that was in about 1980, but it explains some properties of the standard C and POSIX library (e.g. why stat() does not return a 'struct stat').

Why learn C? (O'Reilly Radar)

Posted Jul 1, 2012 22:38 UTC (Sun) by juliank (subscriber, #45896) [Link]

I'd say another reason is that it's much easier to check for errors if your function returns some integer and passes the real result via a pointer.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 9:29 UTC (Mon) by nix (subscriber, #2304) [Link]

Well, if there's only one error, it's easier to use the function if you just return the pointer or NULL.

Structures and results

Posted Jul 12, 2012 16:44 UTC (Thu) by alex (subscriber, #1355) [Link]

Or to emulate old-school styles return NULL and set the global errno ;-)

Why learn C? (O'Reilly Radar)

Posted Jul 12, 2012 20:04 UTC (Thu) by hummassa (subscriber, #307) [Link]

HRESULT feelings.

Why learn C? (O'Reilly Radar)

Posted Jul 12, 2012 20:08 UTC (Thu) by hummassa (subscriber, #307) [Link]

> On the stack of course.

Actually, IIRC, if the struct/class instance fits in one or two registers, those are used to return it; if it does not fit, the caller reserves the space just below the return address/stack frame on the stack (so the callee knows where to put it).

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 18:22 UTC (Fri) by HenrikH (guest, #31152) [Link]

I am not denying reality one bit, I actually only made a reflection upon the real reality, i.e I constantly compare my work, the time it takes me to write certain things and when I compare that with the people who use those so called modern languages I can see no advantage for them, i,e they do not finish their project faster than me and their software is not more capable than mine. The only reason that I stopped writing dynamic web sites in C is that installing new code is such a hassle compared with say PHP since it has to be compiled to the correct architecture.

Impossible to do string handling? I do string handling all the time and I'm sure a lot of other C programmers do the same. Excuse me but what are you smoking?

Arbitrary-precision arithmetic? I just use GMP for that if we are talking about serious need for precision.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 18:44 UTC (Fri) by HelloWorld (guest, #56129) [Link]

> I am not denying reality one bit, I actually only made a reflection upon the real reality, i.e I constantly compare my work, the time it takes me to write certain things and when I compare that with the people who use those so called modern languages I can see no advantage for them, i,e they do not finish their project faster than me and their software is not more capable than mine.
Even if what you say is true, it's just an anecdote with no representativeness whatsoever.

> Impossible to do string handling?
I didn't say that. I said it's impossible to do it in a sane way, and anything that requires you to worry about memory management is *not* sane.

> Arbitrary-precision arithmetic? I just use GMP for that if we are talking about serious need for precision.
GMP-based code is utterly unreadable due to the lack of automatic memory management and operator overloading. Anybody who denies this probably has no idea what good, elegant and simple code looks like.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 17:13 UTC (Sat) by HenrikH (guest, #31152) [Link]

>Even if what you say is true, it's just an anecdote with no representativeness whatsoever.

Of course but I have yet to meet anyone that can write a similar application in another language quicker than I do in C, and I have worked on thousands of projects.

>I didn't say that. I said it's impossible to do it in a sane way, and anything that requires you to worry about memory management is *not* sane.

No you say that You have the right to define what is sane or not and thus it doesn't matter what the rest of us say, it will always be defined as not sane by you.

>GMP-based code is utterly unreadable due to the lack of automatic memory management and operator overloading. Anybody who denies this probably has no idea what good, elegant and simple code looks like.

GMP has automatic memory management under the hood, there is no need to resize the integers etc, and while there is no operator overloading I hardly think that "mpz_add (a, b, c);" is that much harder to read than "a = b + c;".

Actually I think that the first is easier to read since I know by reading the code that the function that performs the action is mpz_add() while I in the other case has to hunt down what class is used, what the overloads are etc.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 18:54 UTC (Fri) by metan (guest, #74107) [Link]

> Impossible to do string handling? I do string handling all the time and I'm sure a lot of other C programmers do the same. Excuse me but what are you smoking?

I must agree with this statement. Most of the rants about C string handling comes from people who couldn't do string handling correctly in any language.

The standard C library sucks, but you could easily do better and even create wonders with reasonable usage of alloca() and some of the C99 features or GNU extensions.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 0:51 UTC (Sat) by alankila (subscriber, #47141) [Link]

Most of us who have written scripting languages do not even think about the concept of "string handling". It doesn't even occur to us that there could be a problem with it.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 3:23 UTC (Sat) by jamesh (guest, #1159) [Link]

You can easily run into problems with languages with automatic string handling if you don't know how the language handles things under the covers.

If you have an algorithm that iteratively cuts off and processes the head of a string until the string is consumed, the way to get the tail of the string can affect the performance.

If making a new string containing the tail of the original string just references the original string data, the obvious solution may work fine. If instead it involves a memory allocation and string copy, then the algorithm may exhibit quadratic performance w.r.t. the string length.

And this isn't just a case of one string handling method being better than the other: with the first strategy, taking a 100 character slice of a 100K string might prevent the large string from being released.

For all its faults, at least these sort of trade-offs are usually visible in C string handling.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 17:03 UTC (Sat) by HenrikH (guest, #31152) [Link]

Exactly, I have encountered numerous people who are baffled when += "some string" all of the sudden gets slow as molasses.

Why learn C? (O'Reilly Radar)

Posted Jul 3, 2012 13:36 UTC (Tue) by alankila (subscriber, #47141) [Link]

*sigh* I should have predicted that my simple comment would end up in this sort of discussion and worse yet would make me look foolish. ;-)

Let's just say that your point is valid and correct. It still does not make me look C-style "string" handling favorably. The few instances where you have to take a copy to detach a substring from a longer string, or to avoid quadratic performance of string concatenation loops are imho not materially significant compared to the benefits of making strings easy and nice to use.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 7:15 UTC (Fri) by ekj (guest, #1524) [Link]

Yes it's really true. At least to the best of our knowledge, it's really true.

I'm not talking "new programmers" here, even the Grand Old Man of large-software projects, Brooks, clearly agrees that high-level languages do allow people to get more done with less hours spent.

It's not a new revelation either, the Mythical Man Month is over 20 years old.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:00 UTC (Fri) by PaulMcKenney (subscriber, #9624) [Link]

Of course, when Brooks wrote "The Mythical Man Month", C was considered to be a high-level language. ;-)

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 23:02 UTC (Fri) by dgm (subscriber, #49227) [Link]

By who? Certainly not by K&R. In the preface of "The C Programming Language" (an absolutely must for anybody wanting to start with C and programming in general) you can read this:

"C is a general purpose programming language which features economy of expression, modern flow control and data structures, and a rich set of operators. C is not a ``very high level'' language, nor a ``big'' one [...]"

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 15:10 UTC (Sat) by engla (guest, #47454) [Link]

“very high level” language and “high level” language are different labels. The former obviously created to differentiate from the latter.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 0:24 UTC (Mon) by rodgerd (guest, #58896) [Link]

So if someone tells you the movie they just watched was "not very good", you'd assume it was a good movie, rather than a bad one?

Why learn C? (O'Reilly Radar)

Posted Jul 4, 2012 12:25 UTC (Wed) by jwakely (subscriber, #60262) [Link]

There's a difference between not very high level and not "very high level"

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 20:05 UTC (Thu) by slashdot (guest, #22014) [Link]

Well, obviously knowing how CPUs work and how they are usually programmed is kind of important for an expert programmer, and you just learn C as part of that.

But of course, if you are a non-programmer trying to write some program as fast as possible, learning C is probably not the best route, and you are probably better off learning the basics of an high-level language, and proceeding mostly by Google search + copy&paste.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 20:10 UTC (Thu) by helge.bahmann (subscriber, #56804) [Link]

While he already mentions the simplicity of the language as a plus, I think that this point can hardly be over-stated for didactical purposes: In a typical course you have half a year to teach one random language to a bunch of students who may not have done any programming before (and some may not be going to after).

With C I found it possible to make the presentation "complete" in the sense that it really covers all logical and syntactical aspects of the language, so students should "in principle" be able to understand almost any code in C at the operational level. (It is of course impossible to teach sane software design within the same single course).

There are good arguments to prefer other languages that make students more productive quicker (found python to be good in this regard), but I found that this inevitably leaves a lot more loose ends (in the sense of: "there is something going on behind the scenes that we have no time to talk about").

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 21:44 UTC (Thu) by ableal (guest, #57174) [Link]

For a moment there, I thought someone had a named a new language "C?"

Close call.

Why learn C? (O'Reilly Radar)

Posted Jun 28, 2012 23:44 UTC (Thu) by zlynx (subscriber, #2285) [Link]

"C ? C : !C" would be a fine name for a language.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 17:53 UTC (Fri) by Nico57 (guest, #63763) [Link]

I guess you must be true. :)

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:18 UTC (Fri) by tjc (subscriber, #137) [Link]

Until you had to give a talk and figure out how to say it. Or google it.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 21:51 UTC (Fri) by zlynx (subscriber, #2285) [Link]

To C or not C. That is the question.

Why learn C? (O'Reilly Radar)

Posted Jun 29, 2012 22:05 UTC (Fri) by man_ls (subscriber, #15091) [Link]

See-why-see-colon-not-see. Hey, there are precedents: C# got away with a stupid C-based naming scheme.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 18:01 UTC (Sat) by tjc (subscriber, #137) [Link]

Hey, as a musician, I like the name C#! I don't know the language (as a matter of principle), but I do like the name.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 18:14 UTC (Sat) by Trelane (subscriber, #56877) [Link]

As a musician, I prefer D♭ over C♯.

Why learn C? (O'Reilly Radar)

Posted Jun 30, 2012 18:23 UTC (Sat) by man_ls (subscriber, #15091) [Link]

"C-sharp" would have been nice. C# is not cool. Not to search, not to write, not to anything.

Bleh, what can you do in a world where Google engineers name a language "Go", throwing googleability to the wind.

Why learn C? (O'Reilly Radar)

Posted Jul 2, 2012 22:19 UTC (Mon) by mathstuf (subscriber, #69389) [Link]

> Bleh, what can you do in a world where Google engineers name a language "Go", throwing googleability to the wind.

I can't help with "googleability", but for "searching", use one[1] that understands conflated terms.

[1]https://duckduckgo.com/?q=go

Thanks, but only partial success

Posted Jul 2, 2012 22:25 UTC (Mon) by man_ls (subscriber, #15091) [Link]

The header explanation on your link is nice, but then the trick is just to search for "Go programming language", something I could do myself in Google. In fact clicking on "Go (programming language)", the second link is for an unrelated language and the fifth conflates totally unrelated terms together.

Thanks, but only partial success

Posted Jul 3, 2012 0:09 UTC (Tue) by hummassa (subscriber, #307) [Link]

Golang works better... :-D

Why learn Fortran?

Posted Jun 29, 2012 0:49 UTC (Fri) by daniel (subscriber, #3181) [Link]

Why not learn every legacy language? C++ completely and utterly obsoletes C except for legacy applications and a few small areas where C is superior, designated intializers for example. Otherwise, C is just for legacy C applications.

Why learn Fortran?

Posted Jun 29, 2012 2:29 UTC (Fri) by dskoll (subscriber, #1630) [Link]

In order to learn C++, one must first learn C.

The article title is "Why learn C?", not "Why use C and not C++?"

Why learn Fortran?

Posted Jun 29, 2012 5:17 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link]

It might be better to skip plain C simply to avoid picking up bad habits (like using raw pointers).

Why learn Fortran?

Posted Jun 29, 2012 15:25 UTC (Fri) by dskoll (subscriber, #1630) [Link]

I disagree. You need to learn about pointers or else C++ will be completely mysterious... you won't have a good understanding of what's really going on under the hood.

Why learn Fortran?

Posted Jun 29, 2012 17:38 UTC (Fri) by daniel (subscriber, #3181) [Link]

You can learn about pointers and arrays perfectly well in C++. In fact nothing stops you from writing C in C++ to your heart's content. However for the inveterate C programmer such as myself there is just so much more that you will never fully understand without actually doing it.

Why learn Fortran?

Posted Jun 29, 2012 22:45 UTC (Fri) by dskoll (subscriber, #1630) [Link]

Again: The title of the article is "Why learn C?"

I'm a programmer, not a teacher, but it seems to me a pretty reasonable way to learn C++ is first to learn C and then to learn what C++ adds on top of C (as well as the points of difference between the languages.)

Why learn Fortran?

Posted Jun 30, 2012 8:35 UTC (Sat) by HelloWorld (guest, #56129) [Link]

> I'm a programmer, not a teacher, but it seems to me a pretty reasonable way to learn C++ is first to learn C and then to learn what C++ adds on top of C
C++ doesn't just add on top of C, it replaces tons of stuff in the sense that while these things still exist, their use is frowned upon due to the presence of better alternatives. Therefore, it actually doesn't make sense to learn C first. Been there, tried that.

Why learn Fortran?

Posted Jun 30, 2012 13:24 UTC (Sat) by dskoll (subscriber, #1630) [Link]

You cut out the parenthetical part of my statement pointing out the areas of difference.

Tell me, are you a teacher or a programmer? Have you taught anyone to program?

I am not a teacher, but I have taught a few people to program, and IMO learning C first and then C++ makes a whole lot of sense, especially if it's a non-programmer doing the learning.

Why learn Fortran?

Posted Jun 30, 2012 13:52 UTC (Sat) by HelloWorld (guest, #56129) [Link]

> You cut out the parenthetical part of my statement pointing out the areas of difference.
That's because the issues I am referring to aren't an area of difference. Malloc exists in C++ and works the same as in C, so clearly there is no difference in that regard, and yet, malloc shouldn't be used in most C++ code.
There are areas of difference between C and C++ (such as the implicit conversion from void* to foo* and a few others), but that really isn't the issue.

> I am not a teacher, but I have taught a few people to program, and IMO learning C first and then C++ makes a whole lot of sense,
Just tell me why. I don't think that teaching people tons of stuff that they'll inevitably have to unlearn later on makes any sense.

Why learn Fortran?

Posted Jun 30, 2012 21:30 UTC (Sat) by dlang (✭ supporter ✭, #313) [Link]

Good programmers should learn many programming languages, as such the first one they learn should not need to be the one they will be using to make a living.

C has the advantage that it's small enough that you can teach the complete language in a short time (when was the last time you saw a language book as small as the K&R C book?, or even one only double it's size?)

That's a huge advantage for a first language.

The fact that other languages work differently just means that when you move on to those languages, you should be learning the new stuff, but already have a solid grounding in the basic stuff.

My High School computer classes started by teaching Basic, then had a class in algorithms, and then covered assembly, and only then branched out to other languages. It resulted in a much more solid grounding, and much more flexible thinking than would come out of any of the College programs I have seen.

Why learn Fortran?

Posted Jul 1, 2012 10:45 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> Good programmers should learn many programming languages, as such the first one they learn should not need to be the one they will be using to make a living.
>
> C has the advantage that it's small enough that you can teach the complete language in a short time (when was the last time you saw a language book as small as the K&R C book?, or even one only double it's size?)
The Little Schemer, the Lua 5.1 Reference Manual. If the goal is to learn programming in general, I'd say that these language make much more sense than C -- no need to bother with memory management, mysterious bugs due to out-of-bounds memory access or C's idiosyncratic syntax and the preprocessor.

On the other hand, if your goal is to learn C++, learning C first doesn't make any sense either due to the reasons mentioned earlier. So unless you actually want to read or write C code, I don't see a reason to learn C.

Why learn Fortran?

Posted Jun 29, 2012 16:33 UTC (Fri) by tshow (subscriber, #6411) [Link]

A colleague of mine and I once spent a week building a memory allocation annotation system to track down a heisenbug that turned out to be a C++ class miscast. C++ will not save you there.

C vs. C++ vs. ...

Posted Jun 29, 2012 11:14 UTC (Fri) by dps (subscriber, #5725) [Link]

C vs.C++ is a flame war I try to keep out of... but the idea that C++ makes C obsolete is nonsense. In my experience a modern C program executes faster than a modern C++ program, due to the extra scaffolding of the latter. C is also probably easier for compilers to optimise---reasoning a reference count is useless might require global analysis.

Sane use of char * can be *much* faster than std::string if you want to transform a string in in way not built into std::string without preserving the original. This was 30%+ of a real program until I aggressively optimised in a way impossible with std::string and reduced it to under 1%.

The more extreme OO people claim OO makes all other styles of programming obsolete and some even think program should be modelled as communicating concurrent objects. The later is completely stupid: this mathematically much harder to analyse than sequential programs.

When the OO people claim I should use objects like sets, queues, lists, maps, etc to simplify programming I agree. When they say how these are implemented does not matter I part company: once I know what operations are important that is a good clue about the right implementation technique.

I not infrequently end up wanting an extended type, for example a tree with subtree size information, or a fast version of a specialised operation. If you can't use a low level language and have a requirement like this then you lose completely when this happens.

When speed is not critical and a high level language is a big win I often use it. A lot of my time is spent writing python code which makes extensive use of dictionaries. The same program in C or C++ would be unlikely to use dictionaries.

C vs. C++ vs. ...

Posted Jun 29, 2012 17:26 UTC (Fri) by daniel (subscriber, #3181) [Link]

"In my experience a modern C program executes faster than a modern C++ program, due to the extra scaffolding of the latter."

Your experience is lying to you. If you write the same program in C and C++ and compile it with GCC you will get the same object code because they use the same code generator and optimizer. Even exceptions these days are compiled so that exception handling generates code only on the throw path, and of course you can compile C++ without exceptions at all. The "extra scaffolding" you speak of does not exist, unless you ask for it and that is entirely up to you.

C vs. C++ vs. ...

Posted Jun 29, 2012 17:52 UTC (Fri) by wahern (subscriber, #37304) [Link]

If you're not using C++ features, then don't use C++.

C++ as C sucks. C++'s conversion rules work well for C++ code, not for C. C++'s type tagging works for C++, not C.

If you want to code in C, use C. If you want C++, use C++. If you want Lua, use Lua. Although, for my money I'll take C and Lua/Perl/Python, and just skip C++ altogether. For many of the things that C++ does better, other languages do better still. So I don't bother, but that's just me.

However, it's really annoying when people argue that you can use C++ just like C. No, you can't. They're completely different languages. extern "C" does not drop you down into "C" mode.

And I don't care if g++ can produce the same output some of the time for equivalent constructs. I can make GCC produce the same code, once sitting in my chair and once while standing on my head. But why would I do that?

C vs. C++ vs. ...

Posted Jun 29, 2012 21:33 UTC (Fri) by daniel (subscriber, #3181) [Link]

"If you're not using C++ features, then don't use C++"

Wouldn't that be a self fulfilling prophesy?

C vs. C++ vs. ...

Posted Jun 29, 2012 18:10 UTC (Fri) by tshow (subscriber, #6411) [Link]

It is not "entirely up to you" unless you're the only person on your project, or unless you're empowered to behead infidels on your team.

Unfortunately, that's exactly the argument I've heard from every C++ evangelist on every project I've ever seen converted to C++. Six months later, the project compile time has gone from 30 seconds to half an hour, the number of lines of code in the project has gone up by an order of magnitude, and the codebase is almost functionally back to where it was when the project was converted from C.

There's nothing intrinsically wrong with C++ when it's used properly. The problem is that all the features that C++ adds to C encourage abuse, and it's hard to find programmers with self control.

On one game console (PS2) project I worked on, for example, the system was converted to C++ partway through the life of the project. One of the guys decided that it would be an excellent idea to wrap the whole project in a class, so he could create an instance of the game and stick all the init code in the constructor. And of course, it had to be a singleton class, so it had extra frippery in it to conform to the design pattern.

It didn't change the functionality at all, it just added crud to the code and the runtime to satisfy someone's broken idea of elegance.

On the same project, we needed to take debug input from the keyboard. There was a small API for that; it should have (and later was) just a matter of calling that API with a little custom command shell. The first crack at it, though, was taken by another of our C++ guys, who decided that the *real* problem was that we needed a key input-handling class hierarchy with templating and several levels of inheritance before we finally got down to a singleton class wrapping the API. I presume if we'd let him continue he'd have given similar treatment to the command shell. Instead, I ripped out (IIRC) 6 files and more than 50K lines of code (before template expansion) and replaced it with about 20 lines of functionally equivalent C.

Even in the hands of good programmers, C++ has nonobvious costs. One of the biggest performance problems on modern hardware is memory access speed; the more you can keep things operating out of cache, the faster things go. C++ template programming and STL encourage a programming style that ignores this. STL in particular is egregious for performance costs due to cache thrashing.

The problem is, someone will go and write a pair of simple programs, one of which does a string sort in C, and one of which does the equivalent in STL. The two will run at about the same speed, if the programmer is competent and honest. The erroneous conclusion that gets drawn from this is that the two have identical performance characteristics.

The C++ program will be larger, and will eat more cache. In a toy benchmark program that isn't particularly noticeable, but once you've scaled up to the size and functionality of a full program it becomes a serious performance hit. Cache thrashing kills you. Making things worse, the problem will likely have metastasized to the point where it's not even obvious what happened. The interwoven class hierarchy and (usually) STL dependency of the project makes it impossible to even contemplate simplifying.

C vs. C++ vs. ...

Posted Jun 29, 2012 21:33 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link]

Stop spraying FUD, please. Almost everything you say is just plain wrong.

C vs. C++ vs. ...

Posted Jun 29, 2012 22:48 UTC (Fri) by dgm (subscriber, #49227) [Link]

No way, the guy is right on the spot.

Object orientation is about abstraction and information hiding. When you need pure speed, hiding information gets in your way, because it prevents optimization. When you need maintainability, though, it can become very handy... if used correctly. What he says about abstraction-creep (AKA over-engineering) is absolutely true. I have seen just too many cases of MVC used to handle simple input dialogs that I don't find it funny anymore.

But, as always, the problem is not with the language, which is just a notation. The problem is poor programming. C is no exception here too. Every time I see sprintf used like this:

sprintf(some_struct.some_member, "%s", some_string);

something breaks inside of me.

C vs. C++ vs. ...

Posted Jun 29, 2012 22:54 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link]

Object orientation is not about hiding something, but about organizing things so they stay manageable.

Besides, modern C++ actually encourages separation of data and algorithms.

C vs. C++ vs. ...

Posted Jun 30, 2012 7:12 UTC (Sat) by khim (subscriber, #9252) [Link]

Besides, modern C++ actually encourages separation of data and algorithms.

Which lead to aforementioned phenomenon you've called FUD. As as guy who recently converted our performance-critical piece of code from C to C++ and achieved 10x smaller code and 10x faster execution time (both are NOT exagerration: it's quite literally 10x+ smaller and 10x+ faster... has more features, too) I observe this every day. Our "C++ guys" continue to complain that 1000 lines function with dozens of macroses is just ugly, but for some strange reason their 10'000 of classes spread of dozens of files should be considered as "elegant". I guess it's partially matter of the opinion but 10x difference in speed is objective thus we are proceeding with C++ to C switch (for that particular component) anyway.

C vs. C++ vs. ...

Posted Jun 30, 2012 8:23 UTC (Sat) by HelloWorld (guest, #56129) [Link]

Your comment is self-contradictory. Did you switch from C to C++ or vice versa?

If you switched from C++ to C, then the only explanation for that phenomenon is poor developers.

C vs. C++ vs. ...

Posted Jul 1, 2012 18:52 UTC (Sun) by khim (subscriber, #9252) [Link]

Your comment is self-contradictory. Did you switch from C to C++ or vice versa?

From C++ to C, of course.

If you switched from C++ to C, then the only explanation for that phenomenon is poor developers.

Not really. The difference is subtler. C++ code uses nice, buzzword-compliant "flexible" architecture (similar to the style showed here). C code uses (as I've said) large functions and macroses. Instead of 10 layers of indirect functions is has dozen of flags (which are processed by said macroses).

This means that it's impossible to do many things with C module which were possible with C++ module - and this is good thing. Because it means that instead of abusing callbacks to do something strange and exciting people need to change the core - which then means that code will be reviewed by people who know how said core works. Which in turn means that fewer stupid things will be introduced in the system.

C vs. C++ vs. ...

Posted Jul 1, 2012 19:16 UTC (Sun) by HelloWorld (guest, #56129) [Link]

> From C++ to C, of course.
Well, you wrote that you converted the code from C to C++.

> Not really. The difference is subtler. C++ code uses nice, buzzword-compliant "flexible" architecture (similar to the style showed here). C code uses (as I've said) large functions and macroses. Instead of 10 layers of indirect functions is has dozen of flags (which are processed by said macroses).
>
> This means that it's impossible to do many things with C module which were possible with C++ module - and this is good thing. Because it means that instead of abusing callbacks to do something strange and exciting people need to change the core - which then means that code will be reviewed by people who know how said core works. Which in turn means that fewer stupid things will be introduced in the system.
Oh, so C is better than C++ because it forces you to program in a certain way that happened to be the right way for your specific case? Sorry, but that doesn't really make sense. What is right for your project may not be right in other circumstances. I prefer a tool that lets me chose the most sensible approach instead of forcing its approach down my throat.

C vs. C++ vs. ...

Posted Jun 30, 2012 8:29 UTC (Sat) by Cyberax (✭ supporter ✭, #52523) [Link]

Uhm. 10000 classes probably mean:
1) Your developers use functors/algorithms implemented as classes and not freestanding functions/lambdas. If they are stateless, then that's just a matter of taste.
2) Your developers in fact do not know how to separate data from algos.
3) Your C code has 10000 structures instead of classes.

C vs. C++ vs. ...

Posted Jul 1, 2012 19:03 UTC (Sun) by khim (subscriber, #9252) [Link]

Uhm. 10000 classes probably mean:

Sorry, I've messed up with relevant sentence. I meant not 10'000 classes (that'll be too extreme of a subsystem to rewrite in one go), but tens of thousand lines (spread over hundred or so small classes in dozen of files).

Your C code has 10000 structures instead of classes.

Not even close. It has couple of structures - but these are only used for testing. Production code just passes data around using regular variables (on registers if you use -O2). This means that a lot of things are just impossible to do without major refactoring/rewriting of the code (because the data is just not available where you need/want to have it), but why is that such a big deal? As long as the API is internal to this piece of code it's not a problem... and when you want to present API to the "outside world" you often want/need C API anyway...

C vs. C++ vs. ...

Posted Jul 1, 2012 19:32 UTC (Sun) by apoelstra (subscriber, #75205) [Link]

The flip side of "data not there when you need it" is that you get much smaller scope (and therefore easier analysis, easier optimization, etc), and you also get guarantees that data will not be modified except by functions who specifically ask for it.

But that is a generic argument against OO-style abstractions, not necessarily an argument specifically for C.

C vs. C++ vs. ...

Posted Jul 1, 2012 20:27 UTC (Sun) by Cyberax (✭ supporter ✭, #52523) [Link]

Again, having code split into small files is just a matter of taste. I prefer my files to be less than 1000-2000 LOCs (especially in plain C), so I can easily navigate them visually. It doesn't affect performance in any way.

C vs. C++ vs. ...

Posted Jul 1, 2012 22:36 UTC (Sun) by juliank (subscriber, #45896) [Link]

Of course it does, if you have many internal functions, you can declare them static, if they are in the same unit. If you split them over multiple files, the compiler cannot inline them and/or the program needs to look them up at run-time (unless you use ELF symbol visibility).

C vs. C++ vs. ...

Posted Jul 1, 2012 22:13 UTC (Sun) by juliank (subscriber, #45896) [Link]

I even have a problem just with people using sprintf(). They should use snprintf().

C vs. C++ vs. ...

Posted Jul 3, 2012 12:39 UTC (Tue) by tshow (subscriber, #6411) [Link]

> Stop spraying FUD, please. Almost everything you say is just plain wrong.

Do you have any actual rebuttals?

C vs. C++ vs. ...

Posted Jun 29, 2012 21:53 UTC (Fri) by daniel (subscriber, #3181) [Link]

...on every project I've ever seen converted to C++. Six months later, the project compile time has gone from 30 seconds to half an hour, the number of lines of code in the project has gone up by an order of magnitude, and the codebase is almost functionally back to where it was when the project was converted from C.

Anecdotes are wonderful aren't they? Even better than statistics for proving pet points. Interestingly, one of my projects supports modules written in either C or C++. I just ran a compile speed bakeoff between some representative files with equivalent number of lines. Result: gcc compiles 2.4 times faster than g++. I would qualify that with "if you don't go crazy with templates". I believe you will find this result quite reproducible. It is a far cry from the factor of 60 you claim.

As for number of lines of code, in every case where I have converted a C program of any complexity to C++, the program has gotten smaller, sometimes by a significant amount like 50% in cases where I was beating my head against the wall hacking up object style inheritance in C.

As far as functionality goes, I think it took me roughly a day to convert a good sized C project of 20K LOC to "C in C++", at which point the functionality is obviously equivalent. Of course it did not stay as C-in-C++, it actually began to accrete new functionality at a rate that was hitherto impossible in its C form.

I would submit that where your experience is different there is something wrong with the engineering process, not the language platform.

What is Science?

Posted Jun 30, 2012 0:59 UTC (Sat) by Wol (guest, #4433) [Link]

JUST A BUNCH OF ANECDOTES!

Which are then studied, analyzed, and used to predict the future.

If the future is successfully predicted, then we have a workable scientific theory.

It really annoys me when people say "that's just an anecdote". No it isn't! It's a data point! It may be an outlier, it may be invalid, it may be wrong, but it is also well known that people will dismiss inconvenient data points without seriously trying to understand them. Feynman gives a very good example of a rogue data point setting quantum mechanics or something like that back 20 years - they didn't bother to see if any data points were rogue, so the "wrong" answer was used and messed up everything else until the problem was spotted - MANY years down the line.

Anyways - my take on this high/low-level stuff? For any given programmer, their productivity measured in LOC is roughly constant regardless of the language. If it takes 10 lines of C or 100 lines of C++, use C. You'll get it done in one tenth the time. On the other hand, if it takes 10 lines of C++ or 100 lines of C ... you get my drift.

Cheers,
Wol

What is Science?

Posted Jun 30, 2012 1:41 UTC (Sat) by Cyberax (✭ supporter ✭, #52523) [Link]

>On the other hand, if it takes 10 lines of C++ or 100 lines of C ...
Usually it's the other way around..

What is Science?

Posted Jun 30, 2012 8:15 UTC (Sat) by HelloWorld (guest, #56129) [Link]

That can't possibly be true. Everything that can be done in C can be done in C++, and more.

What is Science?

Posted Jun 30, 2012 8:27 UTC (Sat) by Cyberax (✭ supporter ✭, #52523) [Link]

I'm speaking about rewrites in "C++ style", not simple "recompile with g++" rewrites.

They do tend to shrink amount of lines of code quite significantly.

What is Science?

Posted Jun 30, 2012 8:39 UTC (Sat) by HelloWorld (guest, #56129) [Link]

You're contradicting yourself. Wol said "if it takes 10 lines of C++ or 100 lines of C", you said "it's the other way around..", and now you're saying that rewrites in C++ style tend to shrink the amount of code.

What is Science?

Posted Jun 30, 2012 22:00 UTC (Sat) by Cyberax (✭ supporter ✭, #52523) [Link]

Yes, rewrites in modern C++ tend to shrink code significantly compared to plain C. There's no contradiction.

What is Science?

Posted Jul 1, 2012 10:17 UTC (Sun) by HelloWorld (guest, #56129) [Link]

Uh, yes there is, unless my english parser is utterly broken, but I don't think so.

What is Science?

Posted Jun 30, 2012 8:28 UTC (Sat) by khim (subscriber, #9252) [Link]

This depends on your design very much. If you've dreamed up nice buzzword-compliant architecture of your project with classes, delegates and other such things then usually C++ code is smaller. If you instead will think about the task on hand and remove all the useless abstractions then often the end result will be less buzzword-compliant yet much smaller.

Of course you can write similar code in C++, but it'll not be "ideomatic C++".

What is Science?

Posted Jun 30, 2012 8:44 UTC (Sat) by Cyberax (✭ supporter ✭, #52523) [Link]

Uhm. Why classes are 'buzzword'? They are, like, 30 years old buzzword. In fact, even in languages like Java/C# architects now try to separate data from functionality (Fowler calls that 'anemic domain model'). And I don't understand that bit about 'useless abstractions'. For example, this kind of code:
std::function<void(int,int)> point_callback;

struct dist_summator
{
   Double dist;
   void add_point(double x, double y, double z)
   {
      dist+=sqrt(x*x+y*y+z*z);
   }
};

dist_summator sum;
point_callback=boost::bind(&dist_summator::add_point, &sum, _1, _2, 123.0d);
...
//Get points
...
//Use sum.dist
Is worse than something like this:
(void)(void*, int, int) point_callback;
void * point_callback_ctx;

typedef struct _dist_summator_with_fixed_z_ctx
{
   double sum;
   double fixed_z;
} dist_summator_with_fixed_z_ctx;
void sum_x_y(void *ctx_ptr, int x, int y)
{
   dist_summator_with_fixed_z_ctx *ctx=(dist_summator_with_fixed_z_ctx*)ctx;
   ctx->sum+=sqrt(x*x+y*y+ctx->z*ctx->z); //Whoopsie, forgot about ints here!   
}

dist_summator_with_fixed_z_ctx ctx;
point_callback = &sum_x_y;
point_callback_ctx = &ctx;
//Get points
...
//Use ctx.sum

What is Science?

Posted Jul 1, 2012 5:50 UTC (Sun) by wahern (subscriber, #37304) [Link]

Both of those examples are really ugly. Arguing that one dog is uglier than the next is kind of pointless.

What is Science?

Posted Jul 1, 2012 15:16 UTC (Sun) by hummassa (subscriber, #307) [Link]

Otoh they are close-to-what-I-have-found-IRL many, many times in the last 20 years.

What is Science?

Posted Jul 9, 2012 5:27 UTC (Mon) by daniel (subscriber, #3181) [Link]

And the C example is actually prettier than plenty of kernel code that does similar things.

What is Science?

Posted Jun 30, 2012 19:28 UTC (Sat) by Kluge (guest, #2881) [Link]

"Feynman gives a very good example of a rogue data point setting quantum mechanics or something like that back 20 years - they didn't bother to see if any data points were rogue, so the "wrong" answer was used and messed up everything else until the problem was spotted - MANY years down the line."

Reference?

What is Science?

Posted Jun 30, 2012 23:40 UTC (Sat) by Wol (guest, #4433) [Link]

It's mentioned in "Surely you're joking, Mr Feynman" or "What do you care what other people think"

But it was something like someone did an experiment to determine the spin of some particle. There was one data point that was way out, and actually was sufficient to dominate the result. Unfortunately it was the wrong result.

However many years it was, down the line, Dick looked at what he was doing and said "hey, if that particle was actually the opposite spin, everything would make sense". Then he went back to the original proof and said "hey, I remember thinking that proof was screwy, when it first came out!". Then he actually checked the maths, and said "ooopppsss".

Cheers,
Wol

What is Science?

Posted Jul 1, 2012 11:15 UTC (Sun) by man_ls (subscriber, #15091) [Link]

For any given programmer, their productivity measured in LOC is roughly constant regardless of the language.
Easy there. That is one of the foundations of function points, as seen in Casper Jones' "Applied Software Measurement"; and it is also utterly wrong. Otherwise we would all be programming in "5th generation languages", i.e. Excel macros.

If you want anecdotal evidence, my productivity (measured in LOC/day) in Perl or in assembly is abysmal. On the other hand, in PHP my productivity is insanely great writing garbage that doesn't work, just great for working code, but if I want to develop tight code then it becomes glacial. In Java it is great but diminishing asymptotically as I approach correct, maintainable code.

There are also serious arguments: high-level languages are less important for productivity than high-level frameworks which do everything for you, be it in C, Python or Excel. But the quality of the framework then becomes the dominant factor; if it takes ages to track down frequent bugs then productivity plummets faster than a sheep from a tree. As we have not yet invented measures for framework quality or completeness, the question of productivity remains completely open and mostly independent of the language.

In time I have learned to distrust frameworks, especially when they are high level. (By the way, I contend in passing that PHP is a framework rather than a language.)

C vs. C++ vs. ...

Posted Jun 30, 2012 2:50 UTC (Sat) by slashdot (guest, #22014) [Link]

The problem seems to be in the hiring process, not in the language choice.

C vs. C++ vs. ...

Posted Jul 4, 2012 20:16 UTC (Wed) by ReadWrite (guest, #85472) [Link]

My observation is good quality code written in C++ is more scalable and easy to extend than written in C. where it involves large amount of configuration/parameter data, I would rather use C++. I have seen many examples where there is no intention to improve or re factor badly structured C programs, so that only the original developer knows the code and he /she can only fix any bug in the code, and that provides job security. Engineering or non Engineering managers alike are only interested in the functionality, and are interested in the performance only when it becomes a commercial issue. A well structured good performing code is not rewarded in fact is seen as taking too long to complete for a minor functionality, or if it can be extended, updated by other developers, that implies it was not very complex in first place . As the common saying goes "Bad programmers become Managers",

If performance to the microsecond is not an issue, I Would be tempted to develop in C++, but again I can mix C(for performance) and C++(for extendability).

C vs. C++ vs. ...

Posted Jul 4, 2012 21:17 UTC (Wed) by dgm (subscriber, #49227) [Link]

> good quality code written in C++ is more scalable and easy to extend than written in C.

If you reword it like "C++ offers you more tools to write more scalable and easy to extend code", then I agree with you. How do you use those tools is up to you, and mastering them takes time, it's not easy to learn when to chose one option over others.

C vs. C++ vs. ...

Posted Jul 9, 2012 5:44 UTC (Mon) by daniel (subscriber, #3181) [Link]

"If performance to the microsecond is not an issue, I Would be tempted to develop in C++"

Having spent a couple of years in the high frequency trading business profiling and optimizing everything to the nanosecond I can state with confidence that the C and C++ code I wrote executed at precisely the same speed, but the C++ was shorter, easier to read, more maintainable and far easier to extend to new functionality.

C vs. C++ vs. ...

Posted Jul 1, 2012 15:43 UTC (Sun) by nix (subscriber, #2304) [Link]

If you write the same program in C and C++ and compile it with GCC you will get the same object code because they use the same code generator and optimizer.
That's wrong: some transformations are done at the language-dependent tree stage, and these can differ between C and C++. Further, the languages have distinct constraints on the optimizer. e.g.:
Even exceptions these days are compiled so that exception handling generates code only on the throw path
That's wrong: C++ code that doesn't use exceptions can still have them thrown through it at any points not marked nothrow (or marked as extern "C" or something similar to indicate the impossibility of exceptions emanating from those points), so not only are cleanup regions required, but a large number of additional abnormal edges are introduced which can and do constrain the optimizer. Thus, you'd often get different code compiling C code as C versus compiling it as C++, even if the optimizers and code generators were completely identical.

C vs. C++ vs. ...

Posted Jul 4, 2012 12:52 UTC (Wed) by jwakely (subscriber, #60262) [Link]

marked as extern "C" or something similar to indicate the impossibility of exceptions emanating from those points
extern "C" doesn't mean any such thing.
#include <stdio.h>
struct E { };
extern "C" void f();
int main()
{
    try {
        f();
    } catch (const E&) {
        puts("Caught");
    }
}
extern "C" void f() { throw E(); }

C vs. C++ vs. ...

Posted Jul 4, 2012 13:37 UTC (Wed) by andresfreund (subscriber, #69562) [Link]

As far as I can see this is undefined behaviour because youre throwing an exception through C linkage which the stack unwinding/exception propagation process doesn't have to be able to do.

C vs. C++ vs. ...

Posted Jul 4, 2012 15:10 UTC (Wed) by nix (subscriber, #2304) [Link]

It's not undefined behaviour so much as it might just not work. Some functions in glibc (e.g. qsort()) are explicitly compiled with -fexceptions so as to support C++ exceptions thrown through qsort() from the callback function, but this is very rare: I've never seen it in C code outside glibc, even for C functions that invoke callbacks.

C vs. C++ vs. ...

Posted Jul 4, 2012 15:17 UTC (Wed) by andresfreund (subscriber, #69562) [Link]

Why is that a contradiction to being undefined behaviour?

C vs. C++ vs. ...

Posted Jul 4, 2012 18:30 UTC (Wed) by jwakely (subscriber, #60262) [Link]

1) I never claimed it had to work, my point is that extern "C" does not mean "cannot throw".

2) It doesn't _have_ to work, but it can work (which would make it closer to implementation-defined or conditionally-supported, not undefined) and does with (at least) GCC, Clang and Solaris CC. There's even a cross-platform standard describing it. For a nice overview of the "personalities" that are used to support mixed-language exceptions to propagate through call frames using different languages see http://llvm.org/docs/ExceptionHandling.html

C vs. C++ vs. ...

Posted Jul 4, 2012 15:08 UTC (Wed) by nix (subscriber, #2304) [Link]

Oooh. Interesting. Given that 99% of C libraries are not compiled with -fexceptions and do not specify anything nothrow-related in their prototypes (of course not, they're C), this suggests that G++ is introducing a very large number of unnecessary abnormal edges for exceptions potentially raised in calls to such functions that cannot possibly ever be thrown. I wonder how much this is impairing optimization?

C vs. C++ vs. ...

Posted Jul 4, 2012 15:51 UTC (Wed) by scottt (subscriber, #5028) [Link]

> Given that 99% of C libraries are not compiled with -fexceptions

Note that Red Hat and Fedora has been building the whole distro with -fexceptions for years:

rpmbuild --showrc | grep cflags
-14: __global_cflags	-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions <...>
I suspect other distros do the same.

C vs. C++ vs. ...

Posted Jul 4, 2012 18:43 UTC (Wed) by jwakely (subscriber, #60262) [Link]

Doesn't the stack have to be unwound similarly for thread cancellation?

The C frames don't need to do any cleanup (no destructors) and should just let the exception propagate unhindered, until it reaches a frame with the right C++ personality to handle it.

I might be completely wrong, but I don't see any obvious reasons the generated code should be different.

Why learn Fortran?

Posted Jun 30, 2012 20:59 UTC (Sat) by cmccabe (guest, #60281) [Link]

> Why not learn every legacy language? C++ completely and utterly
> obsoletes C except for legacy applications and a few small areas
> where C is superior, designated intializers for example. Otherwise,
> C is just for legacy C applications.

I disagree with your opinion that "C++... obsoletes C."

However, this is all off-topic here, because the article is about "why learn C?" and learning C is a prerequisite for learning C++.

Why learn Fortran?

Posted Jul 19, 2012 12:37 UTC (Thu) by philomath (guest, #84172) [Link]

"C++ completely and utterly obsoletes C except for legacy applications"

Thanks for the good laugh, it made my day.

Why learn Fortran?

Posted Jul 21, 2012 12:53 UTC (Sat) by hummassa (subscriber, #307) [Link]

Don't sweat it -- many people will think the joke is on you! :-D

Why use C?

Posted Jun 29, 2012 7:04 UTC (Fri) by niner (subscriber, #26151) [Link]

I'm looking for arguments for a discussion on why someone would want to still use C nowadays. This question will inevitably come up at my bachelor's exam and I would like to answer with something other than just "because the project was started in C 10 years ago".

I know the kernel guys like C for it's explicity which makes it simpler to predict the code generated by the compiler and thus it's performance implications.

Why use C?

Posted Jun 29, 2012 8:57 UTC (Fri) by metan (guest, #74107) [Link]

Well perhaps some of us are comfortable with plain C. Don't get me wrong I could handle variety of languages and each has its place, but when I'm about to write fast algorithm that reads data, does some calculations and writes the result, C is most of the time the choice (because there is nothing that C++ could do better).

And also note that C is not dead language, the standard is evolving C99 is much better than C89 and C11 even has 'type generic expressions' heck the syntax is wrong but its there.

Not to mention that combination of C and inline assembler is best choice for small MCUs where space and timing really matters.

Why use C?

Posted Jun 29, 2012 11:39 UTC (Fri) by alankila (subscriber, #47141) [Link]

What C11 brings to table might be interesting 10 years from now, seeing that C99 still isn't acceptable for many cross-platform projects because the compilers do not implement it.

Why use C?

Posted Jun 29, 2012 11:55 UTC (Fri) by niner (subscriber, #26151) [Link]

Well compilers do. Microsoft's Visual Studio C compiler doesn't. And as they've pretty much officially confirmed, that they won't support C99, chances are, they will never support C11 either. So in 10 years, the situation will be pretty much the same as today: either you want to support this compiler and adhere to an ancient C standard or you don't and have access to a language that's quite ok.

With gcc being available for Windows for free and the possibility to compile as C++ in VC, I really don't see the point of restricting oneself to the stone age.

Why use C?

Posted Jun 29, 2012 16:31 UTC (Fri) by tshow (subscriber, #6411) [Link]

There is to the best of my knowledge no gcc for Microsoft's hardware platforms. If you need to build on XBox 360 or WinPhone, gcc isn't there to help.

Why use C?

Posted Jun 29, 2012 13:45 UTC (Fri) by tshow (subscriber, #6411) [Link]

Because C is available on every platform you might wish to target, which is not true of any other language.

Want to be on Linux? *BSD? Windows? OSX? C is there for you.

Want to run on Wii, PS3, XBox 360, Nintendo DS, DSi, 3DS, PSP or PSVita? C works on all of them, and is the native language of the API on most.

Want to be on iOS, Android or Blackberry? C works fine on all of them.

No other language lets you hit all of those platforms without major hassle. Even C++ is more trouble than C, partly because of implementation differences and partly because in some cases (ie: iOS, where the native language is ObjectiveC) you're working with the fact that the native language of the platform API is one of C's superset descendants.

Our game engine runs on most of the platforms above, with more than 95% of the code being common. The iOS port took almost no time at all, because pure C builds just fine in ObjC. If you want to see Stockholm Syndrome in action, read the forums where people were building C++ projects as ObjC++ on iOS, or (if you have access) trying to get STL working usefully on Nintendo DS. Both can (and have) been done, but the effort expended in the process was instructive.

C also has another advantage; while it lacks some "modern" conveniences (ie: stuff that has been available in LISP since ancient times), that lack makes it easy to do some things that are difficult in most higher level languages. Sometimes you really do need to do low-level memory management, for example, and while garbage collection is an excellent thing to have, not every language that provides it lets you carve off a contiguous chunk of memory and manage it directly.

C also understands binary data natively, which can be a serious advantage in some situations. The perl-esque pack() and unpack() disaster many languages seem to rely on for accessing binary data are awful compared to read(file, &record, sizeof(record));.

None of this is to say that C is some sort of ultimate ideal language. When I'm going to do heavy string processing, or have to deal with yaml or xml or a spreadsheet full of data I'll usually reach for Ruby. I love using lisp and variants when I can. I'm really liking the direction Go is headed in, and I'm somewhat hopeful it can finally be the descendant of C that we should have had 20 years ago.

C also has weaknesses you need to compensate for if you're going to use it cross-platform, chiefly related to data type sizes and alignment.

But C is available everywhere, and it does the job. That really isn't true of any other language currently.

Why use C?

Posted Jun 29, 2012 19:42 UTC (Fri) by dashesy (subscriber, #74652) [Link]

Good points! C is instruction-agnostic assembly language. You can write C code to run on almost any micro-controller and the result is almost the same as direct assembly. I used C for 8951, because assembly code is hard to remember and maintain and saving few bytes is not worth it. If I want to target a *real* embedded system with known and limited memory, or where code reuse is not good (a firmware) I choose C, but trying to use C to write GUI is insane.

I think part of the reason many people are scared of Linux desktop is the old crappy looking GUI toolkits they saw 10 years ago in their college, and modern and shiny GUI like Qt needs a higher level languages.

Why use C?

Posted Jun 30, 2012 1:04 UTC (Sat) by Wol (guest, #4433) [Link]

If you're targeting hardware with little ram, use Forth! :-)

Anecdotes again :-) but a competent Forth programmer should be able to produce code that's smaller than the equivalent assembly!

A Forth executable is, by it's very nature, stripped of pretty much all extraneous stuff, and very compact into the bargain. So much so that it's very hard for an assembler programmer to keep their version down so small.

Cheers,
Wol

Why use C?

Posted Jul 6, 2012 14:09 UTC (Fri) by jflasch (subscriber, #5699) [Link]

Why is "C is available everywhere" it seems this discussion about C has missed this critical point and I wonder why ?

OK the answer "C" major design point was to write a language that was easy to build a compiler for thus "C" was the most successful language to be ported to new hardware out there. Because it had no strong copyrights and easy to use compiler tools like Lex, Yacc it was successful. The language it's self is no big deal, but the portability was.

I'm amazed that no one in this long discussion pointed this 1 big fact out "C" became popular not because it was better , but because it was there and that was due to it's major design point, it was easy to build a compiler for. I guess programmers don't know history well.

Why use C?

Posted Jul 6, 2012 14:37 UTC (Fri) by Cyberax (✭ supporter ✭, #52523) [Link]

Pascal compilers are even easier. Yet Pascal was never really successful.

Why use C?

Posted Jul 6, 2012 15:16 UTC (Fri) by jflasch (subscriber, #5699) [Link]

"C" gave away the yacc and lex syntax Pascal was based on ALGOL 60 which was not so easy of a language, Pascal was highly popular as a PC language but the Unix world never came to it, so I guess "C" also had this Unix bias that kept it going along with easy porting. GCC was a large part of the porting thing, of course. It's funny that the GNU pascal compiler is written in C, then so is Perl and how many other languages , I still think this was more about compilers (IE being there) then syntax.


Why use C?

Posted Jul 6, 2012 17:37 UTC (Fri) by BlueLightning (subscriber, #38978) [Link]

Pascal compilers are even easier. Yet Pascal was never really successful.

Depends how you define successful. Delphi was quite a successful, at least in terms of people using it to produce real software, and that was based on Pascal.

Why use C?

Posted Jul 10, 2012 9:03 UTC (Tue) by anselm (subscriber, #2796) [Link]

Pascal compilers are even easier. Yet Pascal was never really successful.

Yes, but that didn't have anything to do with the compiler – it was really because, unlike C, Pascal was originally supposed to be a teaching language, and lacked many important features it would have needed to succeed in the »real world«, like the idea of libraries or a workable string type. Pascal in its original, official form as described by Jensen and Wirth was good for writing toy programs but not a lot else.

Many of the missing features were added after the fact by various Pascal implementations, but there was little if any standardisation of these extensions. When Donald E. Knuth implemented the second version of TeX in the early 1980s, he solved that problem by basically inventing a new language, WEB, that compiled to his system's version of Pascal, but he still had to jump through various fiery hoops to make that work. (The first version of TeX had been written in a different language altogether.)

As a matter of fact, also in the 1980s Niklaus Wirth, the inventor of Pascal, came up with an improved version of Pascal called Modula-2, which corrected some of the more egregious errors and oversights of the original and was in fact intended to be a language for serious development. However, by that time everybody was becoming sold on the idea of OOP, which Modula-2 quite intentionally didn't support, so that language didn't really go anywhere, either.

Why use C?

Posted Jul 10, 2012 11:59 UTC (Tue) by dgm (subscriber, #49227) [Link]

From my days of Modula2 and Pascal, I vividly remember the feeling that the languages went through leaps and bounds to -limit- you. In hindsight, it probably is a good idea if what you want to do is code from 9 to 5, and then go home to play with your family. But the fact is that the feeling pissed me off then, and was one of the reasons I preferred C and later C++.

Why use C?

Posted Jul 10, 2012 12:52 UTC (Tue) by Cyberax (✭ supporter ✭, #52523) [Link]

For me, in hindsight, almost none of Pascal's or Modula's limitations make sense. They just seem petty and trivial.

Why use C?

Posted Jun 29, 2012 15:10 UTC (Fri) by etienne (subscriber, #25256) [Link]

C is also abused more easily than C++, and it is maybe what you need (for a kernel).
I mean, to run a C application you should have a linear memory which is always accessible, you should have a predictable flow of execution, and few more "obvious" things (like having the same assembler instruction set during the execution of the whole program - no switch from ia32 to amd64).
Unfortunately for kernels, there are a lot of types of memory (virtual,physical,kernel,user,not-present,...), there are non-predicatble flow of execution (interrupts, processor exceptions which are completely different to C++ exceptions), you cannot rely that your stack is "as assumed" by the language - so most of the time you cannot use the cleverness of a language more advanced than C.
For instance, it would be very difficult to handle a C++ exception happening inside a processor exception or a processor interrupt, the stack rollback will not go past. Also do you deviver the C++ exception to the kernel or to the user mode application?
Obviously you do not want to garbage collect the virtual memory which is not yet mapped because it does not exist.
Also, there is a lot of different pointers (some of them 48 bits for high memory), you do not want your class to do a memory access without being sure that the right memory segment is mapped - and C++ may hide some access.
Accessing memory with DMAs (and chained DMA) may also have strange behavior not miximg well with the "detail hiding" of C++.

Was my £0.02...

Why use C?

Posted Jun 29, 2012 22:00 UTC (Fri) by daniel (subscriber, #3181) [Link]

If you don't know exactly what code your compiler produces, whether C or C++, maybe you should seek some more forgiving project than the kernel.

Why use C?

Posted Jun 30, 2012 8:44 UTC (Sat) by HelloWorld (guest, #56129) [Link]

> If you don't know exactly what code your compiler produces, whether C or C++, maybe you should seek some more forgiving project than the kernel.
That's ridiculous. Nobody knows exactly what code exactly a modern compiler will produce for any non-trivial piece of code, including the compiler's authors.

Why use C?

Posted Jun 29, 2012 22:03 UTC (Fri) by daniel (subscriber, #3181) [Link]

"it would be very difficult to handle a C++ exception happening inside a processor exception or a processor interrupt, the stack rollback will not go past. Also do you deviver the C++ exception to the kernel or to the user mode application"

None of the above. You compile with exception handling disabled.

Why use C?

Posted Jun 29, 2012 22:10 UTC (Fri) by daniel (subscriber, #3181) [Link]

"you do not want your class to do a memory access without being sure that the right memory segment is mapped - and C++ may hide some access."

C++ does not have a monopoly on hiding memory accesses, or bugs for that matter. I have even heard of such things cropping up in C code, in the kernel even. Improved programming discipline usually seems to be the cure.

Why use C?

Posted Jun 29, 2012 16:12 UTC (Fri) by cmorgan (guest, #71980) [Link]

I ask myself the same question all of the time. Lots of programmer time is being dumped into backfilling a language like C that doesn't exactly help much with string management, memory management etc.

There are a TON of people that haven't bothered to learn about other languages, including C++.

The other issue I see (from embedded software development) is that some companies are using some really constrained systems that can't support virtual machines or interpreted languages.

Why use C?

Posted Jun 30, 2012 8:56 UTC (Sat) by khim (subscriber, #9252) [Link]

I ask myself the same question all of the time. Lots of programmer time is being dumped into backfilling a language like C that doesn't exactly help much with string management, memory management etc.

Joel answers it best, as usual: I am actually physically disgusted that so many computer science programs think that Java is a good introductory language, because it's "easy" and you don't get confused with all that boring string/malloc stuff but you can learn cool OOP stuff which will make your big programs ever so modular. This is a pedagogical disaster waiting to happen. Generations of graduates are descending on us and creating Shlemiel The Painter algorithms right and left and they don't even realize it, since they fundamentally have no idea that strings are, at a very deep level, difficult, even if you can't quite see that in your perl script.

There are a TON of people that haven't bothered to learn about other languages, including C++.

That's separate issue. People often forget that efficiency or the program in not the target function. Target function is "efficiency of programmers PLUS efficiency of user of said program". If there are millions of users then C makes perfect sense, but when there are only dozens of users (e.g. when said users are programmers involved in the same project) then efficiency of programmer becomes more important and there are plethora or languages which try to improve it (at the expense of resulting program efficiency and thus efficiency of user).

The other issue I see (from embedded software development) is that some companies are using some really constrained systems that can't support virtual machines or interpreted languages.

This, again, shows the same basic misunderstanding. It may be cheaper to buy dozen of high-end appliances and save on programming time. But if you want to produce millions of them then additional month spending on C programming can easily save millions of dollars in the end.

Why use C?

Posted Jun 29, 2012 18:00 UTC (Fri) by apoelstra (subscriber, #75205) [Link]

You can fit the entire memory model in your head. You can fit the machine model in your head. It's a very simple, easy-to-use language. (Some languages *cough*PHP*cough* do not even have a consistent machine language.)

It's also complete enough to use any programming paradigm you want, without preferring one version over the other. Many "better" languages make you use class-based OO, if you want OO (and sometimes even when you don't!).

The standard library is sorely lacking, but there are more libraries available for it than for any other language. It has compilers for more platforms than any other language. It can link with any other language since it doesn't require name-mangling, hidden structures, GC tagging, etc.

The type system is pretty irritating, but it has 'const', which many languages lack, which makes reasoning about code a million times easier than without it.

Why use C?

Posted Jun 29, 2012 21:31 UTC (Fri) by tjc (subscriber, #137) [Link]

Reducing this to a single sentence, C is currently the best available software abstraction of the Von Neumann architecture.

Why use C?

Posted Jun 29, 2012 22:13 UTC (Fri) by daniel (subscriber, #3181) [Link]

"Reducing this to a single sentence, C is currently the best available software abstraction of the Von Neumann architecture."

According to who?

Why use C?

Posted Jun 30, 2012 18:03 UTC (Sat) by tjc (subscriber, #137) [Link]

I thought that would be obvious, since I posted it. ;)

Why use C?

Posted Jul 9, 2012 5:21 UTC (Mon) by daniel (subscriber, #3181) [Link]

Well then I must compliment you on your skillful trolling style.

Why use C?

Posted Jul 1, 2012 6:06 UTC (Sun) by wahern (subscriber, #37304) [Link]

FWIW, C is carefully defined to work just as well on Harvard architectures. That's why there's no conversions allowed between object and function pointers.

Also, you can't compare pointers which aren't derived from the same object. Which means the address space isn't necessarily flat, either.

Why use C?

Posted Jul 1, 2012 22:44 UTC (Sun) by tjc (subscriber, #137) [Link]

Yes, I believe you are right. I was actually thinking of the broader definition of Von Neumann vs. Turing Machine rather than the more specific case of Von Neumann vs. Harvard. In other words, a system with a CPU, registers, and random-access memory.

Somewhere in this video he claims that there are only two foundational languages, C and Lisp, and I think that nails it pretty well. I'm sure there are people who would take umbrage with that claim.

Why learn Forth?

Posted Jul 1, 2012 16:55 UTC (Sun) by forthy (guest, #1525) [Link]

I've tried to learn C first, before I learned Forth. I didn't quite understand. After I learned Forth, I did understand. C is quite close to the machine, but it also is an Algol descendant and tries to hide some things. Like what an address really is - a number, pointing to a byte in the byte-array we call memory (wider accesses take multiple bytes).

Forth's VM is certainly closer to the machine than C's. As is the programming language - no syntax clutters the relation between code and how it is executed. And due to the interactive nature of Forth, it encourages discovering the machine, something C doesn't.

When it is about teaching, I'm strongly in favor of teaching simple model-like languages first. A language close to the machine is important, as the student needs to understand reality. Abstractions are fine for big tasks, but in Java code, I've the impression that people try to abstract the work away - they push it further and further by wrapping the reality in layers and layers of abstraction (but someone has to do the work, after all, so this solves nothing).

Copyright © 2012, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds