-
recursion help
hello,
i am obviously missing a big point on recursion.
this is an excercise program that prints to the screen one char at a time. the return value is the number of chars entered.
all works fine and well until i decide to add the printf at the end of the function, which prints the the chars in the previous functions. the question is, why does the return value change once the printf is enabled?
thanks!
(written with borland c builder)
#include <conio.h>
#include <stdio.h>
int func(int);
void main(void)
{
int d=func(0);
printf("\ndepth=%d",d);
getch();
}
func(int d)
{int x;
printf("%c",x=getch());
if (x!=' ') func(d+1);
else
return d;
//printf("%c",x);
}
-
Code:
func(int d)
{
int x;
printf("%c",x=getch());
if (x!=' ') func(d+1);
else return d;
//printf("%c",x);
}
You should have gotten a warning from your compiler along the lines of "warning: 'func' not all control paths return a value;" As you can see, if you execute the recursive call, then the whole else part is not going to be executed and you will not be returning a value. You should probably change this line:
Code:
if (x!=' ') return func(d+1);
Of course then the extra printf isn't going to help you at all since it will never be executed.
[edit]I tried things both ways (original and extra return like I had) and it didn't seem to affect the results. I did not try out that extra printf however, just seeing if the extra return would change things... it did not. But, it is best to pay some attention to your compilers warnings.[/edit]
-
First off, please use code tags.
Second, your code only works by fluke. func() _must_ return a value, but your if...else...
statement does not necessarily return a value. the line d=func(0) actually sets d to the
last value that was returned by a function - since func(0) does not actually return a value
without the added printf() function the last value returned was actually the right answer -
with the added printf() the last value returned came from the printf() which will have
returned 1. Its usually better only to return at the end of a function, rather than having
multiple exit points (others will disagree I'm sure - there are situations where mulitple
returns from a function make the code clearer - but generally speaking...). So here is a
(in my opinion) better implementation of the function:
Code:
int func (int d)
{
int x,r;
printf("%c",x=getch());
if (x!=' ') {
r = func(d+1);
}
else {
r = d;
}
printf("%c",x);
return r;
}