Why are the two following code segments not equivalent?
void print (char* s) {
if (*s == '\0')
return;
print(s+1);
cout << *s;
}
void print (char* s) {
if (*s == '\0')
return;
print(++s);
cout << *s;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since it looks like the OP changed
print(s++)toprint(++s), which is hugely different, here’s an explanation for this new version.In the first example, you have:
s+1 does not modify s. So if s is 4, and you
print(s+1), afterwards s will still be 4.In this case, ++s modifies the local value of s. It increments it by 1. So if it was 4 before
print(++s), it will be 5 afterwards.In both cases, a value equivalent to s+1 would be passed to the print function, causing it to print the next character.
So the difference between the 2 functions is that the first one will recursively print character #0, then 1, 2, 3, …, while the second function prints 1, 2, 3, 4, … (it skips the first character and prints the “\0” afterwards).
Example:
For the
s+1version,print("hello")will result inhelloFor the
++sversion,print("hello")will result inello\0