Functions and Strings

Const parameters

What if you want to avoid copying a large variable but don't want to change it?

Use the const keyword to indicate that the parameter won't be changed.

void printString(const string &str)
{
  cout << str << endl;
}
int main()
{
  printString("This could be a really really long string");
}

Exercise: what will be printed?

string t = "I am really really long string";

void foo(const string &s)
{
  t = "hello";
  cout << s; //hello
}

int main()
{
  foo(t);
  return 0;
}

Exercise: Is this program correct?

string t = "I am really really long string";

void foo(const string &s)
{
  s = "hello"; //error
  cout << s; //hello
}

int main()
{
  foo(t);
  return 0;
}

Exercise: What will be printed?

string t = "I am really really long string";

void foo(string s)
{
  t = "hello";
  cout << s; //"I am a really really long string"
}

int main()
{
  foo(t);
  return 0;
}

Output parameters

Can also pass by reference to return multiple items.

What is the minimum and maximum time to cook for a dish:

void cookingTime(string const &dishName, double &minTime, double &maxTime)
{
  if (dishName == "rice") {
    minTime = 10*60;
    maxTime = 15*60;
  } else if (dishName == "roti") {
    minTime = 1*60;
    maxTime = 1.2*60;
  } else if (dishName == "moong dal") {
    minTime = 20*60;
    maxTime = 40*60;
  } else ..
  ..
  }
}
int main()
{
  double riceMinTime, riceMaxTime, moongdalMinTime, moongdalMaxTime;
  cookingTime("rice", riceMinTime, riceMaxTime)
  cookingTime("moongdal", moongdalMinTime, moongdalMaxTime)
  double totalMinTime = riceMinTime + moongdalMinTime;
  double totalMaxTime = riceMaxTime + moongdalMaxTime;
  cout << "min: " << totalMinTime << endl;
  cout << "max: " << totalMaxTime << endl;
  return 0;
}

Another example: write a function quadratic to find roots of quadratic equations:

ax^2 + bx + c = 0
for some numbers a, b, and c.

Find roots using the quadratic formula:

What parameters should our function accept? What should it return? Solution
/*  
 * Solves a quadratic equation ax^2 + bx + c = 0, 
 * storing the results in output parameters root1 and root2. 
 * Assumes that the given equation has two real roots. 
 */ 
void quadratic(double a, double b, double c, 
               double& root1, double& root2) { 
    double d = sqrt(b * b - 4 * a * c); 
    root1 = (-b + d) / (2 * a); 
    root2 = (-b - d) / (2 * a); 
} 

Good Decomposition

Strings

#include 
...
string s = "hello";
...

Characters: Characters are values of type char with 0-based indexes:

string s = "Hi COL100!";

index       0   1   2   3   4   5   6   7   8   9
character  'H' 'i' ' ' 'C' 'O' 'L' '1' '0' '0' '!'
Individual characters can be accessed using [index] or at:
char c1 = s[3];    //'C'
char c2 = s.at(1); //'i'
Characters have ASCII encoding (integer mappings):
cout << (int)s[0] << endl; // 72