Section 10.5 References in Range-Based For Loops
Back in Sectionย 9.8 we learned about the ranged-based for loop and saw how it could be used to loop through a string:
In that example, we use a character variable,
letter
, to hold the current character. As we iterate through string, letter
stores a copy of that character. That means, if we change letter
inside the loop, it does not change the original string:
However, instead of declaring
letter
as a char
to be a reference to a character (char&
). If we do so, letter is not storing a copy of the current character, it is an alias for the actual current character in the string. So changing it will modify the string:
So this is another valuable use of referencesโto write a range-based loop that can modify the values it is looping through.
You have attempted of activities on this page.