I'm reading C++: How to Program, Ninth Edition by Paul and Harvey Deitel and I've found something that somewhat confuses me on page 114.
The book gives the example code:
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
The book then goes on to say:
Most programmers write the preceding statement as:
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
The two forms are identical except for the spacing and indentation, which the compiler ignores. The latter form is popular because it avoids deep indentation of the code to the right, which can force lines to wrap.
Below that there is a box labelled as Performance Tip 4.1:
A nested if...else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.
I don't really understand this because (I'm assuming that a "series of single-selection if statements" means the second code example, using the if...else if on the same indentation; the style that is very popular) from what I understand about C and C++, when an if statement or one of the following else if statements is tested to be true, the rest of the else if statements aren't even tested, they're just skipped. Wouldn't that be the same as an early exit? Also, the book says that the two forms are identical as far as the compiler is concerned, why would one outperform the other?
Aucun commentaire:
Enregistrer un commentaire