tags:

views:

2439

answers:

24

Although people seem to like to complain about C++, I haven't been able to find much evidence as to why you would want to choose C over C++. C doesn't seem to get nearly as much flak and if C++ has all these problems why can't you just restrict yourself to the C subset? What are your thoughts/experience?


Exact Duplicate: What's the advantage of using c over c++ or is there one?

+33  A: 
  • Because they already know C
  • Because they're building an embedded app for a platform that only has a C compiler
  • Because they're maintaining legacy software written in C
  • You're writing something on the level of an operating system, a relational database engine, or a retail 3D video game.
Joel Coehoorn
Some microcontrollers only have C compilers which really sucks. The basic C++ features (namespaces, classes besides virtual functions, enums, declaring variables elsewhere besides top-of-block) are the most valuable, IMHO.
Jason S
From this it sounds like you would choose C only if there are no reasonable alternatives.
@Joe: aside from the first point, that about sums it up. A lot of the later languages took C and said, 'hey, we can do _better_.'
Joel Coehoorn
Agreed. If you aren't using the sophisticated C++ features, I believe that C++ is monotonically a better C. With the more sophisticated C++ features, things get more debatable, but then the debate is usually versus a higher level of abstraction- e.g., Java.
Paul Nathan
This is the best answer
Lawand
+1  A: 

I would say that C gives you better control over optimization and efficiency than C++ and hence would be useful in situations where memory and other resources are limited and every optimization helps. It also has a smaller footprint of course.

Chris
Can you give examples of these?
Andrew Grant
So the same C code compiled using a C compiler will be more efficient that if compiled using a C++ compiler?
Steve Kuo
The only place where C gives you more control over efficiency is the C99 "restrict" parameter. C++ templates make it very easy to improve efficiency without loss of generality by reducing memory fragmentation and inlining trivial functions/functors.
Tom
Years ago the Linux kernel could be compiled with gcc or g++, but g++ created slower code ( http://www.tux.org/lkml/#s15-3 under "Finally, while Linus maintains the development kernel ..." ).
Max Lybbert
I suppose I was thinking more along the lines of being able to control more of how your code is optimized in C over C++. Much like how a programmer using assembly language can fine tune his or her code more precisely than one using a higher level language.
Chris
+13  A: 

Because they're writing a plugin and C++ has no standard ABI.

Michel
Although true, it's not a convincing reason to stick to C because you can export the necessary functions using C linkage and still keep your implementation in C++.
codelogic
@codelogic - C++ projects tend to export many more types and functions than the equivalent C projects. It's possible to hide this in a final shared library, but it's quite possibly more effort than it's worth.
Tom
tbh not a really good answer but +1 because C++ has no standard ABI (yes .. C++ sucks)
hasen j
+12  A: 

I choose to write in C because I enjoy working with a small, tight language. I like having access to a standard which can be read in a reasonable amount of time (for me -- I'm a very slow reader). Moreover, I use it to write software for embedded systems for which few desirable C++ compilers exist (like some PIC micro-controllers).

Anthony Cuozzo
re: PICs -- I feel your pain. If I ever have to do a lot of PIC code I will probably use the IAR compiler which supports C++. I've used it on the MSP430 and it's pretty nice.
Jason S
+7  A: 

Because they want to use features in C99 that don't have equivalents in C++.


However, there aren't as many C99 features that are useful to C++ as people think at first glance. Variable-length arrays? C++ has std::vectors. Support for complex/imaginary numbers? C++ has a templated complex type. Type-generic math functions? C++ overloaded the standard math functions, causing the same result.

Named initializers? Not in C++, but there's a workaround:

struct My_class_params {
    int i;
    long j;
    std::string name;

    My_class_params set_i(int ii)
    {
        i = ii;
    }

    My_class_params set_j(long jj)
    {
        j = jj;
    }

    My_class_params set_name(std::string n)
    {
        name = n;
    }

    My_class_params()
    {
        // set defaults
    }
};

class My_class {
    My_class_params params;
  public:
    My_class(My_class_params p) : params(p) { }
    ...
};

This allows you to write things like:

My_class mc(My_class_params().set_i(5).set_name("Me"));
Doug
Hear, hear! The lack of named designated initializers in C++ drives me up the wall every time I have to use it.
ephemient
I'm with 100% on the initializers!!!
Judge Maygarden
If you want to initialize a global structure outside of a function (so you can't .set_*()), C++ forces you to use unnamed initilizer syntax, or to write a constructor for your struct. I don't like either of those options.
ephemient
+13  A: 

Linus' answer to your question is "Because C++ is a horrible language"

His evidence is anecdotal at best, but he has a point..

Being more of a low level language, you would prefer it to C++..C++ is C with added libraries and compiler support for extra features (both languages have features the other language doesn't, and implement things differently), but if you have the time and experience with C, you can benefit from extra added low level related powers...[Edited](because you get used to doing more work manually rather than benefit from some powers coming from the language/compiler itself)

Adding links:

Why C++ for embedded

Why are you still using C? PDF

I would google for this.. because there are plenty of commentaries on the web already

Ric Tokyo
What exactly are these "extra added low level related powers" that C has? The examples you pointed to only talk about differences in how they are commonly used.
Eclipse
I did a lot of coding in C, then a brief period of time in C++, then an embarassingly long time with VB, and now I've been using C# for the last few years. I've written a bit of C and C++ code since then and I've realized that C is well-defined and tight, C# is cool and powerful, and C++ just sucks.
CMPalmer
@Josh, I edited the answer to be more clear..the powers come not from the language C or the compiler, but from the experience you might benefit from by doing things *the hard way* (not using extra features from C++)
Ric Tokyo
I've said for years now I'd use C for a small module/driver/plugin and a higher-level language for a real program. I don't see any reason to use C++. Syntax and readability are just horrific. (Actually, I like to use some C++ features in my C progs, just not classes)
Bill K
Linus is not really qualified to speak about the merits of C++. Quoting him as if he was some kind of oracle is just stupid. And the bit about "doing things the hard way" doesn't make sense. There are good reasons to use C, but "it's more work", or "Linus said so" are not among them.
jalf
@jalf, not quoting Linus as if he is some sort of oracle, its good to mention the opinion of a know programmer for his choices in one of the most used programs in the world: the linux kernel. The question asks for opinions (why someone would choose C) its what I aimed to answer.
Ric Tokyo
Linus is a bad source for opinions on C++ because he does not use it and as far as I know, only tried it once in 1990-something.
Zan Lynx
@Zan Linus displayed more self control elsewhere: "We would have liked to use C++ and the extra features it brings, but its harder to see where bad code in C++ than in C". The quote on my answer is a record of an opinion rather than a "follow the leader".
Ric Tokyo
badly worded as it may seem, this is an interesting view from an interesting guy.
Ric Tokyo
+9  A: 

Long compile times can be annoying. With C++ you can have very long compile times (which means, of course, more time for Stack Overflow!).

Why was this voted down? I do a lot of work in C++ myself and I wouldn't go back to C, but it can indeed have painfully long compilation times (think of templates, for example).
I use C++ for real work, but I always prototype in C because of the near-instantaneous compile times.
Tom
+37  A: 

Joel's answer is good for reasons you might have to use C, though there are a few others:

  • You must meet industry guidelines, which are easier to prove and test for in C.
  • You have tools to work with C, but not C++ (think not just about the compiler, but all the support tools, coverage, analysis, etc)
  • Your target developers are C gurus
  • You're writing drivers, kernels, or other low level code
  • You know the C++ compiler isn't good at optimizing the kind of code you need to write
  • Your app not only doesn't lend itself to be object oriented, but would be harder to write in that form

In some cases, though, you might want to use C rather than C++:

  • You want the performance of assembler without the trouble of coding in assembler (C++ is, in theory, capable of 'perfect' performance, but the compilers aren't as good at seeing optimizations a good C programmer will see)
  • The software you're writing is trivial, or nearly so - whip out the tiny C compiler, write a few lines of code, compile and you're all set - no need to open a huge editor with helpers, no need to write practically empty and useless classes, deal with namespaces, etc. You can do nearly the same thing with a C++ compiler and simply use the C subset, but the C++ compiler is slower, even for tiny programs.
  • You need extreme performance or small code size, and know the C++ compiler will actually make it harder to accomplish due to the size and performance of the libraries

You contend that you could just use the C subset and compile with a C++ compiler, but you'll find that if you do that you'll get slightly different results depending on the compiler.

Regardless, if you're doing that, you're using C. Is your question really "Why don't C programmers use C++ compilers?" If it is, then you either don't understand the language differences, or you don't understand compiler theory.

Adam Davis
There's also the MISRA C standard, which AFAIK isn't yet really stable for C++.
Paul Nathan
The performance part isn't necessarily true. There are plenty of areas where C++ can optimize far better than C. (Of course the reverse is also occasionally true, but generally, choosing C over C++ for performance reasons is a bad idea).
jalf
I'd be interested in more performance information. I don't understand why C would only perform better "occasionally." Given an average programmer, it may be that C++ makes performance easier to attain (good use of patterns) but a C program written by an expert should be faster - lower overhead.
Adam Davis
Of course, the faster C program would take longer to write and debug, so there's a tradeoff, and given the speed of machines the tradeoff is rarely worth it except for specialized applications, which is why C++ is generally better. (by the time the code is done, computers are faster and eat the dif)
Adam Davis
But most code written in the world goes into embedded processors, and often there are code size/performance contraints where C shines. Lower power, direct control over the processor and peripherals, etc - sometimes beats out the advantages of C++.
Adam Davis
But I'm not trying to say one is better than the other - in fact, I admit that only under certain circumstances should C be considered as an option. The right tool for the right job...
Adam Davis
@Adam: C++ performs better than C with "pretty" code. C++ can use templates and inline functions where C needs a macro. C++ overhead only appears when asked for, it is otherwise the same as C. (virtual, try/throw, dynamic_cast). Much of the overhead only shows in program image size.
Zan Lynx
@Zan "C++ overhead only appears when asked for, it is otherwise the same as C" Great, I'd really like to see some references.
Adam Davis
@Adam: Personal experience, and to make sure I just compiled an identical hello world C program with gcc and g++ and the object code for main was identical, only a bit of library loading was different. Provide your overhead references.
Zan Lynx
Ah. I'm not trying to start a c vs c++ war here. As I've said earlier, only under certain circumstances would I recommend anyone use C. In general they are on par with each other. But for certain problems C is _sometimes_ a better choice. It's an old tool well past its prime - but still useful.
Adam Davis
+16  A: 

Fears of performance or bloat are not good reason to to forgo C++. Every language has its potential pitfalls and trade offs - good programmers learn about these and where necessary develop coping strategies, poor programmers will fall foul and blame the language.

Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer.

In my industry, video games, we write high performance code in C++ by avoiding things such as RTTI, exceptions, or virtual-functions in inner loops. These can be extremely useful but have performance or bloat problems that it's desirable to avoid. If we were to go a step further and switch entirely to C we would gain little and lose the most useful constructs of C++.

The biggest practical reason for preferring C is that support is more widespread than C++. There are many platforms, particularly embedded ones, that do not even have C++ compilers.

There is also the matter of compatibility for vendors. While C has a stable and well-defined ABI (Application Binary Interface) C++ does not. The ABI in C++ is more complicated due to such things as vtables and constructurs/destructors so is implemented differently with every vendor, and even versions of a vendors toolchain.

In real-terms this means you cannot take a library generated by one compiler and link it with code or a library from another which creates a nightmare for distributed projects or middleware providers of binary libraries.

Andrew Grant
"Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer." I guess a programmer (not necessarily a Python Progammer) that took algorithms lessons can produce code that executes faster than that of an inexperienced developer (in general).
Andrei Ciobanu
A: 

Because you're writing for a system where resources are tight (such as an embedded system, or some kind real bare metal code like a kernel) and you want as little overhead as possible.

There's a reason why most embedded systems don't have a C++ compiler - it's not that people don't want one, it's that cramming C++ code into that small a space is task that approaches impossible.

Electrons_Ahoy
Not really so much a problem of C++ itself as a language, but the pathological bloat that indiscriminate use of templates can cause.
Crashworks
ecos is largely written in C++. There is no relation between the language (compared to C) and executable size (as long as you know what features to use).
"as long as you know what features to use". That's the point - the result of saying "well, we have C++, but we can't support half the language features for overhead reasons" is Symbian/C++, which confuses and angers both C programmers *and* C++ programmers...
Steve Jessop
Agreed on all points. Our solution to "knowing what features to use" was to just use a C compiler and call it a day. Sure, we could have made C++ work, (which would have been really fun in a super-nerd kinda way) but we had a product to ship, and didn't have the time to worry about it.
Electrons_Ahoy
+1  A: 
  • Until some years ago the existing C++ compilers were missing important features, or the support was poor and the supported features vary wildly among them, and so it was hard to write portable applications.
  • Because of the no standard naming of symbols it is difficult for other languages/applications to support C++ classes directly.
Ismael
+1  A: 

There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).

Crashworks
A: 

What C needed was a better preprocessor. cfront was one and thus born c++

I'ld use C, where the 'c++ as preprocessor' would not be okay.

I'm pretty sure, at the bottom of any well written c++ library/framework/toolkit, you would find dirty-old-c ( or static casts, which is same )

Vardhan Varma
+5  A: 

I'm surprised no one's mentioned libraries. Lots of languages can link against C libs and call C functions (including C++ with extern "C"). C++ is pretty much the only thing that can use a C++ lib (defined as 'a lib that uses features in C++ that are not in C [such as overloaded functions, virtual methods, overloaded operators, ...], and does not export everything through C compatible interfaces via extern "C"').

BigSandwich
Not so; you can extern "C" or __cdecl your functions to expose them to C.
Crashworks
Great, but what other languages does that work with?
BigSandwich
a C lib can work in far more places.
BigSandwich
All the ones that can link to C.
Crashworks
extern "C" adn __cdecl wraps a C++ function as if it were a C function. This is how you write libraries in C++ and allow them to be linked through .DLLs or a CLR.
Crashworks
The most obvious reason for interoperability problems is name-mangling, and I think that's worth bringing up.
Tom
+2  A: 

Most of the significant features of c++ somehow involve classes or templates. These are wonderful features except for the way the compiler transforms these into object code. Most compilers use name mangling, and the ones that don't do something at least as messy.

If your system lives on its own, as is the case with many applications, then C++ is a fine choice.

If your system needs to interact with software not neccesarily written in C++ (most frequently in assembler, or Fortran Libraries) then you are in a tight spot. To interact with those kinds of cases, you'll need to disable name mangling for those symbols. this is usually done by declaring those objects extern "C", but then they can't be templates, overloaded functions, or classes. If those are likely to be your applications API, then you'll have to wrap them with helper functions, and keep those functions in sync with the actual implementations.

And in reality, the C++ language provides a standard syntax for features that can be easily implemented in pure C.

In short, the overhead of interoperable C++ is too high for most folks to justify.

TokenMacGuy
I'm very startled to hear this because I've written so many .DLLs in C++ that had extern "C" interfaces so they could be called from C or any other CLR language. Certainly you can't simply expose member function pointers, but it's really not much trouble marshal data for __cdecl calling.
Crashworks
Actually, you can export templated code. It just requires non-templated function wrappers for every type you want to use to avoid name collisions.
Judge Maygarden
+4  A: 

Because for many programming tasks C is simpler, and good enough. When I'm programming lightweight utilities especially, I can feel like C++ wants me to build in an elegant supersructure for its own sake, rather than simply write the code.

OTOH, for more complex projects, the elegance provides more good solid structural rigor than would naturally flow out of my keyboard.

le dorfier
A: 

One remark about "just use the subset of C++ you want to use": the problem with this idea is that it has a cost to enforce that everybody in the project uses the same subset. My own opinion is that those costs are quite high for loosely coupled projects (e.g. open source ones), and also that C++ totally failed at being a better C, in the sense that you cannot use C++ wherever you used C.

David Cournapeau
+2  A: 

I haven't been able to find much evidence as to why you would want to choose C over C++.

You can hardly call what I'm about to say evidence; it's just my opinion.

People like C because it fits nicely inside the mind of the prgrammer.

There are many complex rules of C++ [when do you need virtual destructors, when can you call virtual methods in a constructor, how does overloading and overriding interact, ...], and to master them all takes a lot of effort. Also, between references, operator overloading and function overloading, understanding a piece of code can require you to understand other code that may or may not be easy to find.

A different question in why organizations would prefer C over C++. I don't know that, I'm just a people ;-)

In the defense of C++, it does bring valuable features to the table; the one I value most is probably parametric('ish) polymorphism, though: operations and types that takes one or more types as arguments.

Jonas Kölker
+4  A: 

In addition to several other points mentioned already:

Less surprise

that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).

In many cases this magic is nice, but for example in real-time systems it can really screw up your day.

jdisk
+1  A: 

This is pretty shallow but as a busy student I chose C because I thought C++ would take too long to learn. Many professors at my university won't accept assignments in Python and I needed to pick up something quickly.

vinc456
Wise of your teachers!
Andrei Ciobanu
+3  A: 

I take the other view: why use C++ instead of C?

The book The C Programming Language (aka: K&R) tells you clearly how to do everything the language can do in under 300 pages. It's a masterpiece of minimalism. No C++ book even comes close.

The obvious counterargument is that the same could be said of most, if not all, modern languages -- they also can't tell you how to do everything in only a few hundred pages. True. So why use C++ instead? Feature richness? Power? If you need something more feature rich or powerful then go with C#, Objective C, Java, or something else like that. Why burden yourself with the complexities of C++? If you need the degree of control C++ grants then I argue to use C. C can do anything and can do it well.

Dinah
Well notepad or cat is pretty minimalist but I much prefer the convenience and power offered by more sophisticated editors at the cost of some complexity.
vinc456
I agree. I want power so I use something truly powerful, not the 1/2 way point.
Dinah
@Dinah: The 1/2 way point gives you higher level expression power without the performance and memory cost of C# or Java.
Zan Lynx
@Zan Lynx: you're right. But I hope by taking the opposing stance that I did in my original post that I made a point about the viability of C over C++ ... even if it is, as you point out, not an open and shut case.
Dinah
+1  A: 

If you want your code to be understood by virtually any programmer write in C.

Liran Orevi
+4  A: 

i like minimalism & simplicity.

plan9assembler
OK - fair enough...so why not Forth?
Jonathan Leffler
A: 

Oh my, C vs C++, a great way to start a flame war. :)

I think C is better for driver and embedded code.

C++ has some great features that C doesn't have, but many of the object oriented features of C++ can cause monumental coding messes when people write code with non-obvious side-effects that occur behinds the scenes. Crazy code can be hidden in constructors, destructors, virtual functions, ... The beauty of C code is the language does nothing non-obvious behind your back, thus you can read the code and not have to look up at every constructor and destructor and so on. A lot of the problem is bad coding practices by SOME people.

My perfect language would be a combination of C99 plus a minimal subset of safer C++ capabilities that adds ZERO (or near zero) compiler overhead to the binary output. Perfect additions would be class encapsulation and naming concepts of data and functions.