2

I was reading about "range for" statements when I got confused how it exactly works.

Below is a program to convert a string to Uppercase.

string s("Hello World!!!");

//convert s to uppercase

for( auto &c :s )  // for every char in s
   c= topper(c);   //  c is a reference,so the assignment changes the 
                   //  char in s
cout<< s << endl;

How is the reference to the string (that is, c) is changing elements to upppercase?

I've searched about how iteration could work here, but I couldn't find the answer.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Yogesh Tripathi
  • 703
  • 5
  • 16

2 Answers2

6

This piece of code

for (auto& c : s)
{
    c = toupper(c); 
}

roughly translates to this

for (auto it = std::begin(s); it != std::end(s); ++it)
{
    auto& c = *it;
    c = toupper(c);
}

which is a basic iterator loop, covered in any beginner C++ book.


cppreference has a more detailed and precise explanation.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
2

"c" is not an ordinary variable, it acts as a proxy (or reference) to each element (character) in the string.

By changing "c" you are in fact changing the value which "c" is refering to.

groovyspaceman
  • 2,584
  • 2
  • 13
  • 5