The loop counts from 0 to size() - 1 (< size()). For each of those values, it asks for the character at that index and then prints it. Notice that the counter for this loop is of type size_t. If we try to make it an int, the compiler will likely produce an error or warning when we try to compare it to size(), which is a size_t. Comparing signed numbers - those that can hold negative numbers like int - with unsigned values - those that can only hold positive values like size_t - can produce confusing results.
We could use the same basic loop to modify each character. This program encrypts the string myString (very poorly) by shifting each character by 1 alphabetically:
If we are doing something like printing each character in a string, we donโt actually care about which character is at which index. We just want to do something to each character (print it). There is a syntax to make that easier known as the range-based for loop or enhanced for loop:
You should read that loop as โfor each character, call it c, in myString, do...โ The range-based for loop automatically counts through the characters one by one. For each iteration of the loop, the next character is stored into the character variable declared in the loop. In that example, the character is named c, but you can name it anything you like. Then, in the loop, you can use that character variable to access the โcurrent letterโ. This example uses the ranged-based loop to count the number of spaces in a string:
It is possible to allow changes to the character variable to also change the string. We will cover that syntax later in Sectionย 10.5 For now, if you care about the location of each character, or if you need to change the string as you iterate through it, you should not use a range-based loop.
There is no reason you ever have to use the ranged-based loops, you always can use a regular counting loop that counts from 0 to size() - 1 and index into the string. But the syntax is so simple you likely will want to make use of them.