Sunday, December 9, 2007

Convoluted C++

When reading Bruce Eckel's TICCP volume 1 and doing an exercise on pointers-to-member syntax, I was reminded of one thing I like about Lisp and even more about Scheme: simple syntax. In comparison, C++ is so awful.

For e.g., Ex 25 in Ch 11 of Volume 1 asks us:


Create a class containing an array of int. Can you index through
this array using a pointer to member?


Well, here is the class:

class Foo {
public:
int a[10];
Foo() {
for (int i = 0; i < 10; i++)
a[i] = i;
}
};


Now, how do I declare the pointer-to-member that will refer to a?

After several tries, I got it:
int (Foo::*mem)[10];, which I use like this:
mem = &Foo::a;

I'd tried:

int Foo::*mem;
...
mem = &Foo::a;


and


int Foo::*mem;
...
mem = &Foo::a[0];


and


int Foo::*mem[];
...
mem = &Foo::a[0];

(this crashed the compiler, GCC 3.4.4 on Cygwin)

and


int Foo::*mem[10];
...
mem = &Foo::a;


The point is that special syntax to do everything is so icky once you have tasted Scheme. I'd say half or more of Bruce's book is about the syntax to get to the various features of the language. You are focusing so much on learning syntax that you don't have any time to figure out how you'd use those features for real work. And with the convoluted syntax in your way, you are not likely to be using the appropriate feature where it would be really handy.

Nevertheless, TICPP does and excellent job of just that: describing the language's features and trying to give a scenario where that feature would be useful. Too bad, knowing the features requires memorizing so much syntax. In C, to get to a "feature", I'd just look at the man page for the relevant function. There are no man pages for syntax, unfortunately.

Convoluted C++

Been going through Bruce Eckel's "Thinking in C++" books. I've not programmed in C++ for a while, as I mostly program in Python (and am learning Ruby, Lisp, Erlang, and stuff). However, I felt it would be good to sharpen up my C++ and Java chops.

So, I'd learnt C++ from Bjarne Stroustroup's book a long time ago. I thought I'd covered pretty much the whole book, except multiple inheritance. Alas, I'd learnt little. Well, enough to write a Python extension or two.

Bruce does an excellent job of explaining the language if you are a programmer that already knows C. Otherwise you should go and get familiar with C first. Recommened reading.