I have a real problem with programmers that write obscure code. Just to illustrate what I mean, here are two programs that do exactly the same thing. They calculate the powers of numbers one through ten from the first to the fourth power, and then print the results on the screen.
Tell me which coding is easier to understand: the first one or the second one.
First one:
Code:
#include <stdio.h>
#include <stdlib.h>
int pwr(int a, int b);
int main(void)
{
/* Declare a pointer to an array that has 10
ints in each row. */
int (*p)[10];
register int i, j;
/* allocate memory to hold a 4 x 10 array */
p = malloc(40*sizeof(int));
if(!p) {
printf("Memory request failed.\n");
exit(1);
}
for(j=1; j<11; j++)
for(i=1; i<5; i++) p[i-1][j-1] = pwr(j, i);
for(j=1; j<11; j++) {
for(i=1; i<5; i++) printf("%10d ", p[i-1][j-1]);
printf("\n");
}
system("PAUSE");
return 0;
}
/* Raise an integer to the specified power. */
pwr(int a, int b)
{
register int t=1;
for(; b; b--) t = t*a;
return t;
}
Second one:
Code:
#include <stdio.h>
#include <stdlib.h>
/* function declaration */
int pwr(int power, int base);
int main(void)
{
/* declare a pointer to an array that has 10
ints in each row. */
int (*p)[10];
/* declare row and column variables, respectively */
int i, j;
/* allocate memory to hold a 4 x 10 array */
/*arrays are arranged as array[row][column]*/
p = malloc(40*sizeof(int));
if(!p)
{
printf("Memory request failed.\n");
exit(1);
}
/* In the following for loop, the power is represented by i,
the row of the array; the base is represented by j,
the column of the array.*/
for(i=1; i<5; i++) /* outer loop --> row */
{
for(j=1; j<11; j++) /* inner loop --> column */
{
p[i-1][j-1] = pwr(i, j);
} /* end of inner loop */
} /* end of outer loop */
for(i=1; i<5; i++) /* outer loop --> row */
{
for(j=1; j<11; j++) /* inner loop --> column */
{
printf("%6d ", p[i-1][j-1]);
} /* end of inner loop */
printf("\n");
} /* end of outer loop */
printf("\n\n");
system("PAUSE");
return 0;
}
/* function definition */
pwr(int power, int base)
{
int t=1;
for(; power != 0; power--) t = t*base;
return t;
}