Home Segments Index Top Previous Next

318: Sidetrip

Consider, for example, the following oddball version of power_of_2, in which the decrementing of the counter variable occurs in the Boolean expression, rather than in the normal continuation expression, which is rendered empty. The suffix form, counter--, must be used, rather than the prefix form, --counter, because decrementing is to be done after your program decides whether to go around the loop. Were you to use the prefix form, your program would fail to go around the loop enough times.

int power_of_2 (int n) { 
  int counter, result = 1; 
  for (counter = n; counter--;) 
   result = 2 * result; 
  return result;