abhinav700's blog

By abhinav700, history, 5 days ago, In English

Earlier, i was solving a problem. When i went to discuss section to see the solutions, there was a person who was following a syntax of for loop which i was not able to understand.

it was as follows: for (char &c : word) where word is of type std::string. can someone explain me how is it different from for (char c : word)? because i was getting run time error when i tried to remove & from c.

i tried running it my console, but still was not able to understand it's working properly.

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
5 days ago, # |
  Vote: I like it +1 Vote: I do not like it

You can refer here

»
5 days ago, # |
  Vote: I like it 0 Vote: I do not like it

cunnilingus

»
5 days ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Do share the entire code, without seeing complete code it is impossible to help.

#include <bits/stdc++.h>

int main()
{
    std::string s = "abc";

    for (char ch : s) {
        std::cout << ch << " ";
    }
    std::cout << std::endl;

    for (char &ch : s) {
         std::cout << ch << " ";
    }
}

Both loops works in this case!