take advantage of array indicies

This tip submitted by Dave on 2005-03-28 20:53:47. It has been viewed 36588 times.
Rating of 5.6 with 176 votes



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]]++;




More tips

Help your fellow programmers! Add a tip!