Exercise 3-7 (Strings passed by value, address, reference)
Chapter_3 Exercise_3-6 Function_call | Modifiers Exercise_3-8 |
Exercise 3-7 TCP1, p. 227
Exercise 3-7. Create two functions, one that takes a string* and one that takes a string& as argument. Each of these functions should modify the outside string object in its own unique way. In main(), create and initialize a string object, print it, then pass it to each of the two functions, printing the results.
Strings.cpp download
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
void passByValue(string);
void passAddress(string*);
void passReference(string&);
int main()
{
string str = "Hello!";
cout << str << endl; // Hello!
passByValue(str); // Howdy!
cout << str << endl; // Hello!
passAddress(&str); // Hi!
cout << str << endl; // Hi!
passReference(str); // Halo!
cout << str << endl; // Halo!
return 0;
}
void passByValue(string s)
{
s = "Howdy!";
cout << s << endl;
}
void passAddress(string* sp)
{
*sp = "Hi!";
cout << *sp << endl;
}
void passReference(string& sr)
{
sr = "Halo!";
cout << sr << endl;
}
/*
g++ Strings.cpp -o Strings
./Strings
Hello!
Howdy!
Hello!
Hi!
Hi!
Halo!
Halo!
*/
Chapter_3 Exercise_3-6 Function_call | BACK_TO_TOP | Modifiers Exercise_3-8 |
Comments
Post a Comment