Friday, September 28, 2007

Coding 101

Why do something difficult to read, and completely ineffiecient like:

int i = 0;
int j = 0;

for(i = 0; i < 6; i ++)
{
   for(j = 0; j < 5; j ++)
   {
     if( j < i )
     {
       printf("i - j = %d\n", i - j );
     }
     else if ( i < j )
     {
     printf("j - i = %d\n", j - i);
     }
     else
     {
     printf("j == %d == i\n", j );
     }
   }
}


When you can cut the entire thing down to two logical lines(Yes I know the second line spill over into multiple ones, but it's still just one while loop statement). This greatly enhances readibility, since there are less lines to look over, and enhances performance somehow :-D


int i=0, j=-1;

while( (j++ < 10) && ( j < 5 || ( (i ++ < 5 ) && ((j=0) || 1) )) && ( j < i || j == i || printf("j - i = %d\n", j - i) ) &&
( j > i || j == i || printf("i - j = %d\n", i - j) ) && ( j > i || j < i || printf("j == %d == i\n", j)) ) ;


And yes these are exactly equivalent, and the second one will compile in ANSI C.

0 comments: