Search code examples
c++pass-by-value

C++ string pass by value


C++ string passing by value is puzzling me here. I'm expecting that it prints out aa ab ba bb However, it prints aa aab aba abab. Why does this happen?

std::string s, ab = "ab";
test(s, 0, ab);
void test(std::string s, int i, std::string ab){
    if(i == ab.size()){
        cout << s << ' ';
        return;
    }
    for(auto c : ab){
         s += c;
         test(s, i + 1, ab);
    }
}

If I replace

s += c;
test(s, i + 1, ab);

by

test(s + c, i + 1, ab);

it will work as expected.


Solution

  • When you use +=, you add one character to s in each iteration, so you're passing a longer and longer string to test until all the characters of ab have been appended.

    Perhaps it becomes more obvious if you unroll the loop:

    s += ab[0]; // s is now "a"
    test(s, i+1, ab);
    s += ab[1]; // s is now "ab"
    test(s, i+1, ab);
    ...