-2

I'm new to C++ and is trying to learn the concept of reference. Could someone please tell me why a reference (i.e. &c) is needed to change each character from lowercase to uppercase? Why (auto c : s1) wouldn't work?

int main(){

    string s1 = "hello world";
    for (auto &c : s1){
        c = toupper(c);
        cout << s1 << endl;
    }

    return 0;
}
iksemyonov
  • 4,106
  • 1
  • 22
  • 42

1 Answers1

1

Short answer is, that with auto c, c would be initialized with a copy of each symbol in s1 on every iteration of the for loop. The original symbol in s1 would remain intact. Whereas using a reference, you refer directly to the variable you want to modify, thus, modifying c has the effect of identically modifying the symbol in s1 that c is referring to now. c does not contain a symbol, rather it is a mechanism, used by the compiler, that allows you to avoid creating an unnecessary copy of the data that you want to modify or read.

Refer to this excellent SO discussion:

What's the difference between passing by reference vs. passing by value?

Now, to come back to your code, uppercase and lowercase aren't related to references in any way. (It might seem that you're thinking so by looking at the title of your question.) This is simply an example of modifying an existing array of variables, iterating over it and taking a reference to every element, then performing some task on that element, with the intention to have the original data changed.

Community
  • 1
  • 1
iksemyonov
  • 4,106
  • 1
  • 22
  • 42