"herrcho" <he*********@kornet.net> schrieb im Newsbeitrag
news:bl**********@news1.kornet.net...
int main()
{
printf("Input a line: ");
wrt_it();
printf("\n\n");
return 0;
}
void wrt_it()
{
int c;
if (( c = getchar()) != '\n')
wrt_it();
putchar(c);
}
the above is from 'A book on C'
and it says the function calls are stacked.
i know what stack means. but don't understand how stack is related to
recursion.
Could anyone explain to me about that ? and, why does the input
characters print reversely?
First: the language does not say anything about how parameters are passed.
Fortunately your book says " function calls are stacked", which IMHO has not
necessarily to do with a "stack" like it is used in many, but not all
implementations.
Anyway, parameters must be stored in a last in first out way somehow...
now to your question:
void wrt_it()
{
int c;
if (( c = getchar()) != '\n')
wrt_it();
putchar(c);
}
wrt_it is called from main(), it gets a local copy of c
wrt_it receives one character and stores it in c
let's assume it is not '\n' then
wrt_it calls itself, this new instance gets it's own local copy of
c, to help understanding let's name it c1
wrt_it receives one character and stores it in c1
let's assume it is not '\n' then
wrt_it calls itself, this new instance gets it's own local
copy of c, to help understanding let's name it c2
wrt_it receives one character and stores it in c2
let's assume it is '\n' now, then
wrt_it does not call itself anymore, instead it outputs it's
copy of c (c2)
and returns to the previous instance of itself
the previous instance also outputs _it's_c which is c1 and
returns to the previous instance of itself
this instance again outputs it's own copy of c and returns to the
caller (main() in our example
we are done
Ngngng - hope I got it right (including the formatting) :)
Robert