Debugging question 4

Compile and run the following code:
// if you change t with s in the snippet, the code has the same effect
#include<iostream>
#include<string>

std::string method(std::string& s) {
  s = s.substr(1, s.npos);
  return s;
}

int main(int argc, char** argv) {
  using namespace std;
  string s("ciao");
  cout << s << endl;
  while(true) {
    string& t = s;
    //////////// snippet ////////////////
    t = method(t);
    if (t.length() == 0) {
      break;
    }
    cout << t << endl;
    //////////// end snippet ////////////
  }
  return 0;
}
the output is:
ciao
iao
ao
o
Now examine the part of the code marked ``snippet'': it has the curious property that if you replace any occurrence of the t variable symbol with the s variable symbol, you still obtain the same output. Explain why.



Subsections

Leo Liberti 2008-01-12