2007-02-21

C/C++

I hate that term. People write it on job applications and job specifications. People use it in conversation. People use it on reference sites and books, gah.

I hate it because it gives C++, a lovely language, a bad name. Below are some examples, both of these are nowhere near the most efficient way to do these in either language, but they are the most obvious way, and the ones you're likely to see:

C

#include <stdio.h>

int main() { char name[20];

// Crash here if name > 19 characters:
gets(name);

{
    int length = strlen(name) + 4;

    // Manual memory allocation, no exception safety.. wait, what exceptions?!
    char *row = (char *) malloc(length);
    int i;

    // Clean the memory so strcat works:
    memset(row, 0, length);

    for (i=0; i < length; ++i)
        strcat(row, "*");

    strcat(row, "\n");

    // What does that format string do? Nobody knows.
    printf("%s* %s *\n%s\n", row, name, row);

    // Cleanup:
    free (row);
}

}

C++#include <iostream>

include <string>

using namespace std;

int main() { string name; getline(cin, name);

string row;

for (int i=0; i < name.size() + 4; ++i)
    row += "*";

row += "\n";

cout << row <<
    "* " << name << " *\n" <<
    row << endl;

return 0;

}

I hope, from that, you can see that there's absolutely no similarities at all, in any way, between those two programs (they both do nearly the same thing, differing only in that you can easily crash the C one).

Ignoring the fact that it's simply sane, you get pretty much the entirety of C to play with so, if something is easier to write in C, do so, plus "templates, exceptions, namespaces, constructors/destructors (and therefore RAII), virtual function polymorphism, references, operator/function overloading, reusable standard generic containers, explicitly named casts" and, best of all, Boost.

If you're still not convinced, the closing evidence should be that it took me seven attempts to get the C one not to segfault on run, and the C++ one worked first time. :)


Commenting is disabled for this post.

Read more of Faux' blog