Monday, February 23, 2009

Take advantage of array indicies

When operating on two arrays with the same index and operation, the switch statement can usually be avoided.

Consider the general switch statement that assigns and tallys all the occurrences of array[i] to count[i]:
switch (array[i]) {
case 1: count[1]++;
break;
case 2: count[2]++;
break;
case 3: count[3]++;
break;
/*...
case n: count[n]++;
break;
*/
}

this can be shortened to the single
statement:

count[array[i]]++;
Author : Dave

0 nhận xét:

Post a Comment