24 February 2012

Why I Think C# and Java Trump C and C++

Well the title is a bit sensationalist. As a disclaimer I strongly believe that you need to pick the correct tool that best suits the job at hand and that you believe you will be the most productive in.

However when faced with the agonizing task of printing out Trace messages with variable formatting in a bit of C code that I had lying around recently, I realised just how focused C# is on getting things done rather than faffing about with boilerplate code.

As an example, here are two functions that fundamentally do the same thing, print a formatted string to the system Trace listeners using a single format string and then a variable number of arguments:

First the C# function:
void odprintf(string format, params object[] args)
{
    Trace.WriteLine(string.Format(format, args));
}

Compared to the C equivalent:
void __cdecl odprintf(const char *format, ...)
{
    char buf[4096], *p = buf;
    va_list args;
    int n;

    va_start(args, format);
                             // buf-3 is room for CR/LF/NUL
    n = _vsnprintf(p, sizeof buf - 3, format, args);
    va_end(args);

    p += (n < 0) ? sizeof buf - 3 : n;
    while ( p > buf  &&  isspace(p[-1]) )
            *--p = '\0';

    *p++ = '\r';
    *p++ = '\n';
    *p   = '\0';

    OutputDebugStringA(buf);
}
Really, all this magic is necessary to just print to Trace?

I reserve the right to seriously doubt that "lower" level languages have any place but in highly specialised or those extremely few cases where throughput and latency are more important than developer productivity and deadlines are lax and forgiving.

Here is someone that is more eloquent than I am on this issue.
There is no reason to use C++ for new projects. However, there are existing projects in C++ which might be worth working on. Weighting the positive aspects of such a project against the sad fact that C++ is involved is a matter of personal judgement.

If you end up working with C++, don't try to "fix" it (or "boost" it). You'll just add more layers of complexity. The most productive approach is to accept the problems and try to write simple code which people can easily follow.

If you are an expert in the intricacies of C++, please consider this knowledge a kind of martial art - something a real master never uses.