Reputation: 45
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.
Upvotes: 0
Views: 90
Reputation: 66371
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);
...
Upvotes: 1
Reputation: 2357
s += c;
append c to the local string s in every loop run, so s is modified
test(s + c ...)
append c to the local string s and pass the resulting string, s is the same in every loop run
Upvotes: 2