c++ - Recursive Reverse Function -
i wondering whether explain how small code snippet works.
void reverse(char *s) { if(*s) reverse(s+1); else return; cout << *s; } when call function in main, supposedly prints out reverse of string put in (ie. hello cout olleh) don't understand how. understand it, if statement increases value of s until reaches end of string, printing out each value in string goes. why doesn't re-print string. missing something. (sorry btw, new c++ , recursive functions)
consider how "hello" string stored in memory: let's address of 'h' character happens 0xc000. rest of string stored follows:
0xc000 'h' 0xc001 'e' 0xc002 'l' 0xc003 'l' 0xc004 'o' 0xc005 '\0' now consider series of invocations of reverse: initial invocation passes 0xc000; call of reverse inside reverse passes s+1, next level gets 0xc001; next 1 gets 0xc002, , on.
note each level calls next level, until level sees '\0'. before zero, stack "loaded" this:
reverse(0xc004) // last invocation before hit '\0' reverse(0xc003) reverse(0xc002) reverse(0xc001) reverse(0xc000) // earliest invocation now when top invocation calls reverse(0xc005), check *s fails, , function returns right away without printing anything. @ point stack starts "unwinding", printing whatever pointed s argument:
0xc004 -> prints 'o', returns previous level 0xc003 -> prints 'l', returns previous level 0xc002 -> prints 'l', returns previous level 0xc001 -> prints 'e', returns previous level 0xc000 -> prints 'h', returns good. that's how reverse of original "hello" string gets printed.
Comments
Post a Comment