Incrementing pointers in C++ -
why 2 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; }
since looks op changed print(s++)
print(++s)
, hugely different, here's explanation new version.
in first example, have:
print(s+1); cout << *s;
s+1 not modify s. if s 4, , print(s+1)
, afterwards s still 4.
print(++s); cout << *s;
in case, ++s modifies local value of s. increments 1. if 4 before print(++s)
, 5 afterwards.
in both cases, value equivalent s+1 passed print function, causing print next character.
so difference between 2 functions first 1 recursively print character #0, 1, 2, 3, ..., while second function prints 1, 2, 3, 4, ... (it skips first character , prints "\0" afterwards).
example:
s+1
version, print("hello")
result in h
e
l
l
o
++s
version, print("hello")
result in e
l
l
o
\0
Comments
Post a Comment