Trying to understand this Code

I have been learning on my own. Can't really understand voids. The only thing I picked up from online really is that they don't return any vaule witch is kinda confusing on its own. But this code is just to make caps not matter in a program im trying to make to practice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cctype>
#include <string>
using namespace std;

void toUpper(string&);
void toLower(string&);

void toUpper(string& str)
{
 for (unsigned i = 0; i < str.size(); i++)
 {
    str[i] = toupper(str[i]);
 }
}

int main()
{
   string lookup = "";
   cout << "lookup test type htl";
   cin >> lookup;

   toUpper(lookup);

   if (lookup == "HTL")
   {
      cout << "it worked\n";
   }
   else {cout << "fail\n"; }
}


I understand the looks (until the for loop) what I really dont understand is &str is it saying that str is short for string? I also don't understand the line inside the for loop. Really its just that whole for loop. I need to understand it before I put it in my main code so I dont mess up my main system
Last edited on
void toUpper(std::string str)
Makes a copy of the passed string, any changes the function makes to the copy won't be part of the original string.

https://www.learncpp.com/cpp-tutorial/72-passing-arguments-by-value/

void toUpper(std::string& str)
Passes the string directly into the function, by using a reference to the original string.

Any changes the function makes to the passed string are part of the original string.

https://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

A std::string is a complex data type, copying one is can be a performance hit if you don't need to make a copy.
Topic archived. No new replies allowed.