CS253

CS253: Software Development with C++

Fall 2011

Example String Cast

A String Example

Consider this code--what does it display?

(:source lang=cpp filename=c.cc -inline:)

  1. include <iostream>
  2. include <string>

using namespace std; int main() {

    string a="hello", b=a;
    a[0]='j';
    cout << a << ' ' << b << endl;
    return 0;

} (:sourceend:)

Now, consider this code. This code is evil, because it casts the result of a.data() to be writable. However, its result may be surprising. What does it display?

(:source lang=cpp filename=d.cc -inline:)

  1. include <iostream>
  2. include <string>

using namespace std; int main() {

    string a="hello", b=a;
    char *p = (char *) a.data();
    *p = 'm';
    cout << a << ' ' << b << endl;
    return 0;

} (:sourceend:)

Modified: 2009-02-02T13:40

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building