Archive for the ‘precedence’ Category

bad code?

I’m working getting Jay Fenalson’s hack up and running on OS X Leopard. While debugging the code I ran into this sample code that exemplifies Jay’s coding style which I really don’t like:

for(foo=(int *)levl; foo <= (int *)&levl[NX-1][NY-1]; *foo++ = 0)

Take a good look at that. What the heck is going on? Well, he’s converting levl, which is of type:

struct lev levl[NX][NY];

So really levl is type struct lev ** (well, sizeof would disagree about this as levl is a specific size but for the sake of this discussion struct lev ** is fine). Well, he’s type casting that to int * and putting that into foo. I’ll cover the incr part of the foo loop explaining the test.  He’s checking to make sure foo, which contains the address of an array of lev structures–remember each element of the array is a pointer, doesn’t run off the end of the array of levels.  OK, back to incr expr of the for loop,  *foo++ = 0.  John Ousterhoot said that parenthesis should be added when the order of operations is not clear. Is it clear here?   Obviously the intent is to null the array, the deref occurs first then the assignment and finally the increment (actually the generated code copies foo to a tmp, increments foo and then uses tmp for the deref and then assignment).  Precedence aside,  wouldn’t the code be easier to read if it was:

*foo = 0, foo++;

The comma operator in C, evaluates multiple statements as one statement, using the last statement as the return value.

This is how I tend to write and therefore teach people Perl. Although there is more than one way to do it, it’s not necessarily the right way. Write it readable and  let the compiler take care of the rest. If it’s still too slow, and most likely it isn’t, then go back and optimize.