Loop Body analyzing in C++

timer Asked: Nov 3rd, 2014

Question description

template <class K, class V, class TCompare>
void Map2<K, V, TCompare>::remove (K& key, K& keyFromMap, V& valueFromMap)
	MapPairRecord newItem;
	for(int i = 0; i < mapSize; i++) {
		if(TCompare::areEqual (key, s.entry(i).keyItem)) {
			s.remove(i, newItem);
		} // end if
	} // end for
} // remove

Questions to ask about loops:

  1.)  Is a definite loop used in a situation that calls for an indefinite loop or vice versa?
  2.)  Does the loop body contain 1-time-execute only code, i.e., code that only executes on the last trip through the loop, or only executes the first time through the loop?
  3.)  Is the intent of the loop to do multiple things?
  4.)  Are loop exit conditions hidden in the loop body?
  5.) Is a 1-trip loop used in a situation that calls for a zero-trip loop?
What to do:

  If a loop uses a definite loop where an indefinite loop is called for (or vice versa) change the loop so that it uses the correct loop control construct. For example, if a for-loop is used, but a while-loop is needed switch to a while-loop and carefully craft the loop's conditional to exit the loop body under the correct circumstances.
  If the loop body contains 1-time-execute only code that executes on the last trip (or possibly the first trip), then rework the loop body and move this code outside of the loop body.
  If the intent of the loop is do multiple things, then redesign the loop so that it does one thing well.
  If break or return statements are hidden in the loop body, usually guarded by an if statement, then find a way to re-engineer the loop so that the conditional for the loop is directly dependent on the conditional found in the if statement in the loop body.
  If a 1-trip loop is used when there is a legitimate possibility that zero trips through the loop body may occur, then switch to a zero-trip loop.

Tutor Answer

(Top Tutor) Studypool Tutor
School: New York University
Studypool has helped 1,244,100 students
flag Report DMCA
Similar Questions
Hot Questions
Related Tags

Brown University

1271 Tutors

California Institute of Technology

2131 Tutors

Carnegie Mellon University

982 Tutors

Columbia University

1256 Tutors

Dartmouth University

2113 Tutors

Emory University

2279 Tutors

Harvard University

599 Tutors

Massachusetts Institute of Technology

2319 Tutors

New York University

1645 Tutors

Notre Dam University

1911 Tutors

Oklahoma University

2122 Tutors

Pennsylvania State University

932 Tutors

Princeton University

1211 Tutors

Stanford University

983 Tutors

University of California

1282 Tutors

Oxford University

123 Tutors

Yale University

2325 Tutors