C# vs C++

[Update: Changed a misplaced "C#" to a "C++" in the tools section. Thanks, Nick]

At the class a took a while back, the instructor asked me to talk a little bit about the benefits of C++ vs the benefits of C#, since I had worked in C++, then in C#, and now in C++ again.

I talked for about 5 minutes on why C# was better, in the following themes. Note that I'm speaking about the whole programming environment, not just the language.

Automatic memory management

There are several facets of this. When I read or write C++ code,  I keep part of my attention on the algorithmic aspects of the code, and another part on the memory aspects of the code. In C#, I usually don't have to worry about the memory aspects. Further, in C++ I need to figure out who owns objects and who cleans them up, and also figure out how to clean up in the presence of error checking.

Exceptions

Without a lot of dedication, using return codes is a bug farm waiting to happen. In the C++ world, some functions return HRESULT, some return a bool, some return another set of status code, and some return a number and use an out-of-range value as an error indicator. Oh, and some are void. You not only have to write the correct code there, you have to successfully convert back and forth between the various kinds of error handling.

You also lose the opportunity to write more functional code. I end up writing something like:

CString name;
RTN_ERROR_IF_FAILED(employee.FetchName(name));

instead of writing:

string name = employee.FetchName();

And, of course, exceptions are fail-safe in that you get error reporting without doing anything, rather than having to do everything right to get error reporting.

Coherent libraries

The C++ code I'm writing uses at least 6 different libraries, all of which were written by different groups and have different philosophies in how you use them, how they're organized, how you handle errors, etc. Some are C libraries, some are C++ libraries that are pretty simple, some are C++ libraries that make heavy use of templates and/or other C++ features. They have various levels of docs, all the way from MSDN docs through "read the source" docs to "a single somewhat-outdated word doc".

I've said in the past that the biggest improvement in productivity with .NET comes from the coherent library structure. Sure, it doesn't cover everything in Win32, but for the stuff it does cover, it's often much much easier to use than the C++ alternative.

Compilation Model

C++ inherited the C compilation model, which was designed in a day when machine constraints were a whole lot tighter, and in those days, it made sense.

For today, however, separate compilation of files, separate header and source files, and linking slow things down quite a bit. The project that I'm working on now takes somewhere on the order of a minute to do a full build and link (that's to build both the output and my unit tests, which requires a redundant link). An analogous amount of C# code would take less than 5 seconds. Now, I can do an incremental make, but the dependency tracking on the build system I use isn't perfect, and this will sometimes get you into a bad state.

Tools

Reflection is a great feature, and enables doing a ton of things that are pretty hard to do in the C++ world. I've been using Source Insight recently, and while it's a pretty good IDE, it isn't able to fully parse templates, which means you don't get full autocompletion in that case.

Code == Component

In C#, you get a component automatically. In C++, you may have extra work to do - either with .IDL files or with setting up exports.

Language Complexity

C++ templates are really powerful. They can also be really, really obtuse, and I've seen a lot of those obtuse usages over the years. Additionally, things like full operator overloading are great if you want a smart pointer, but are often abused.

And don't get me started on #define.

The alternate view

So, if what I say above is true, the conclusion looks pretty clear - use C#. Not really much surprise considering who came up with the list.

But there are things that C++ has going for it, and it really depends on the kind of code you're writing which language is a better choice. In broad strokes (and in my opinion, of course), if you're doing user applications (either rich client or web), choosing C# is a no-brainer. When you start getting towards lower-level things like services or apps with lots of interop, the decision is less clear.

So, what do I think you get in C++? A few things spring to mind.

Absolute control over your memory

I think you actually need this level of control much less than you may think you need it, but there are times when you do need it.

Quick boot time

Spinning up the CLR takes extra time, and it's likely to alway take extra time  (unless it's already spun up in some other manner). You don't pay this penalty in the C++ world.

Smaller memory footprint

Since you aren't paying for the CLR infrastructure, you don't pay for memory footprint.

Fewer install dependencies

You can just install and go, and your users don't have to install the proper version of the CLR.

 

So, that's pretty much what I said in the class. What did I miss?

Comments

  • Anonymous
    January 26, 2005
    In the "Tools" section, I think you meant to say:

    Reflection is a great feature, and enables doing a ton of things that are pretty hard to do in the C++ world

    Note the C++, not C#.

    The outcome is not surprizing. You give some interesting points for what C++ offers, but with cost of memory, and Longhorn on the horizon, most of those points will be nullified, I'm assuming (at least on a Windows platform).

  • Anonymous
    January 26, 2005
    C or C++ are NOT application languages People seem to forget that.

  • Anonymous
    January 26, 2005
    Cross platform is a win, unless you are in the embedded market. Put aside the ego and use the right tools for the job.

  • Anonymous
    January 26, 2005
    > What did I miss?

    Templates, template metaprogramming, STL, Boost.

  • Anonymous
    January 26, 2005
    "In the C++ world, some functions return HRESULT, some return a bool, some return another set of status code, and some return a number and use an out-of-range value as an error indicator. Oh, and some are void. You not only have to write the correct code there, you have to successfully convert back and forth between the various kinds of error handling. "

    Right, because these things can't happen in C#....


    Yeah, uh huh.

  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    On the C++ side:
    * Generally better exposure of CLR features, but the gap is small with C# 2.0 vs C++/CLI.
    * A better optimizing profiler.
    * And the big one - PInvoke free interop

  • Anonymous
    January 26, 2005
    Although a .net application uses way more memory it is very smart in using it. I can allocate a 1 000 000 000 byte array without actually needing 1 Gig memory it seems as long as I don't use all of it with C#. Also C#'s GC puts objects that are of the same generation and thus most likely to use eachother close to eachother which makes it a lot faster (CPU loads memory not directly but via the CPU cache which gets a block of a certain size, if that block contains all the objects required you are lucky). Although C++ programmers tend to say the GC is slow is very wrong. The malloc function works a bit like the GC (seeking free space), but it doesn't clean up except when in trouble and then malloc is really slow (the GC of .net outperforms malloc by far).
    And lots of other stuff like efficient optimalization from IL to native images optimised for the cpu currently used by the ahead in time compiler. etc..

  • Anonymous
    January 26, 2005
    What David Brownell said. I would also want to take issue with your statement "In C#, I usually don't have to worry about the memory aspects." I find that in a long-running app (which is what I am working on now), memory management is much harder in C# than it is in C++. I have to worry exactly as much in both environments about who owns every new'ed object, but this is significantly more difficult in C#, where deterministic cleanup has to be the responsibility of clients and can't be encapsulated in the resource owner. Non-deterministic cleanup is taken care of by the GC, but in a long-running app that doesn't help me - I need to know that when I'm done with the thing, it's gone, now. Yes, it's possible to handle these problems through coding standards and thorough reviews - but this is far less effective than the guarantees you get from DD.
    Well, the GC saves me from having to worry about cyclic references. To my mind, it solves a not-very-difficult problem and replaces it with a number of very hard and insidious ones.

  • Anonymous
    January 26, 2005
    Everyone's mentioned template metaprogramming, but I'll throw in my agreement.

    While I'm wholeheartedly convinced that C++ is now a dead language, I really miss two things - templates and const.

    With const, you could write a very safe program, which is nearly impossible to do in C#.

    The power of templates was incredible. I'm a firm devotee of DSL's, and templates really did allow you to basically build your own language - especially combined with typedef and (shock horror) the occasional #define.

    Generics are very good, and essential, but they just reduce the amount of code you write - they don't take any steps towards your own domain specific language - and that's a huge loss IMO.


  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    My preference is for C#, after having worked on C++ for numerous years ( http://weblogs.asp.net/sbchatterjee/archive/2005/01/26/361136.aspx ). Now that C# has evolved with generics - it would be nice to see comparable C# libraries that matches C++'s (incl ATL et al).

  • Anonymous
    January 26, 2005
    Languages are all about the right tool for the right job. Now, C# has made some advancements, making it appropriate for a wider range of jobs, but when we get down to it, you're still not going to write kernel code or device drivers or programs for extremely limited resource systems, where manual memory management is a necessity. As Alex said, the Windows desktop/server world is not all there is.

    On the flip side, there are some great uses for Perl that C# will probably never be able to compete with.

  • Anonymous
    January 26, 2005
    "What did I miss?" Two more for the C# side:

    1. C# avoids many of the dark, obtuse edge cases that follow from the not-quite-ortogonal features of C++. An example is the infamous "What happens when you call an overridden virtual method from a virtual base class's constructor?" By not having virtual base classes and not having weird rules about when overridden methods come into play during construction, C# avoids the issue. There are many, many similar questions in C++.

    2. In modern C++, the obvious tool for the job is seldom the right tool. For example, in the modern world of STL and exceptions, you should almost never use the fundamental types of the language like pointers and arrays. Which leads one to the question "if you're not supposed to used them, why are they there?" C# on the other hand is designed so that the obvious way to code something is usually the correct way.

  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    The comment has been removed

  • Anonymous
    January 26, 2005
    <p>&lt;ul&gt;&lt;li&gt;Nehéz és hosszú szülés után... ami főleg időhiánynak köszönhető... kérjük azokat, akik szívesen olvasnak (=azt a keveset), hogyha talál vmi érdekeset, akár el is küldheti :)&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;ht

  • Anonymous
    January 26, 2005
    "I disagree, the naming is very consistant which is way more important than nice naming although in my opinion .net uses good naming. "
    The naming is not consistent with what the collections actually are.

    I don't give a hoot about internal consistency; what I want is for things to be named what they ought to be named.

    Though the .NET libraries are obviously much larger than the C++ libraries, it seems to me that about as much work went into the design of the C++ libraries as went into the entire .NET class library; the result of this is that the C++ libraries are more expressive and more capable than their .NET counterparts.

  • Anonymous
    January 26, 2005
    I missed the CTS

    (How many different string types are there in C++ again? Ever tried to pass a date(time) to a database?)

  • Anonymous
    January 27, 2005
    It would be nice if you didn't need to force someone to install the entire .net framework because you chose to write in C#.

    Since the framework is not a required download and has never been part of any major patch the majority of the Windows desktop world doesn't have it installed.

  • Anonymous
    January 27, 2005
    http://blog.w-nz.com/archives/2005/01/27/negative-net-myths-busted/

  • Anonymous
    January 27, 2005
    Interesting Finds so far this week

  • Anonymous
    January 28, 2005
    A few people have mentioned a dislike for the lack of deterministic destructors in C#.

    I would like to say that it took me a while before I figured out the beauty of NOT having them. Over time, C++ caused me to blur the concept of 'shutdown my object' with 'free my object memory'. These two items are distinct and different. Now, I 'shutdown my object' and let the OS worry about 'freeing my object memory'. It is rare that I care about the freeing of the memory, but I DO want to know that my object has been shut down.

    Sca

  • Anonymous
    January 29, 2005
    C++ is not a dead language.c# is a version of C++ and has its own loop holes as well.
    In my own opinion C++ will continue to be the best language everywhere,its library its hard-core.You can develop any applicattion you want (i.e: text base and graphical).
    It might be inflexible some somehow especially with its case sensetiveness.

    Programmer Lington(Delphi/c++/Oracle)

  • Anonymous
    February 04, 2005
    I think, both are best. It depends on what will build. Programming language is only a tools. Don't be an extreme programming language. Some can solve many things that some could not. So, it depends on situations. As a technology preview, C# still need evolution(maybe) that makes very..very different from C family. So, what should M$ deals with ?

  • Anonymous
    February 09, 2005
    i have a CPP and H file and also dll created created using the same files.

    insted of this i able to refer the dll into my C# project. it is not work.

    how to convert the cPP and H file into C#

    plz send details about that to Govindarajan@teembrains.com

  • Anonymous
    February 16, 2005
    The comment has been removed

  • Anonymous
    February 16, 2005
    Michael,

    I started to write a comment that addressed your points, but I ended up deleting it to make a general comment instead.

    While you do say some things that are true, it's clear to me from mistakes in your comment that you haven't really used C#.

  • Anonymous
    February 16, 2005
    Sorry, I forgot to say that I haven't used it a lot. I'm still a newbie when it comes to C#, but I've been a professional programmer for the past 10 years and have developed unprofessionally before then.

    Please, feel free to comment and show me where I'm wrong... I'd like to know so I can learn and so other people don't get the wrong ideas from what I said. :)

    The one comment that I know is at least "off base" is the "Small applications have a huge ..." bit... I started rethinking that right after I posted, but thought I'd let others correct me.

  • Anonymous
    February 16, 2005
    The comment has been removed

  • Anonymous
    February 19, 2005
    http://kghsjg.k1.xrea.com/ ,http://hls.k2.xrea.com/ ,http://eom.k2.xrea.com/ ,http://www.soudown.net/ ,http://www.998guide.com/ ,

  • Anonymous
    August 21, 2006
    Being asked this lately I thought I would post it on the blog for everyone to see and decide for themselves.

  • Anonymous
    February 10, 2007
    PingBack from http://forums.fevergaming.com/off-topic/programming-web-development/122259-what-next.html#post1763754

  • Anonymous
    October 30, 2007
    PingBack from http://www.se7ensins.com/forums/programming-support/81624-c-vs-c.html#post622078

  • Anonymous
    December 11, 2007
    PingBack from http://syyedwahab.wordpress.com/2007/12/11/magic-of-c-with-respect-to-c/

  • Anonymous
    January 21, 2009
    PingBack from http://www.keyongtech.com/736774-why-exactly-is-c-better

  • Anonymous
    June 07, 2009
    PingBack from http://greenteafatburner.info/story.php?id=1788

  • Anonymous
    June 08, 2009
    PingBack from http://quickdietsite.info/story.php?id=14356