Reputation: 107
unable to print nothing, even we passed string s.
void reverse(char *s)
{
if(*s)
{
return reverse(s+1);
printf("%c",*s);
}
}
works as exact behaviour, it printing the string in reverse order.
void reverse(char *str)
{
if(*str)
{
reverse(str+1);
printf("%c", *str);
}
}
could anybody know ,what would be the problem for program 1.
I think, in recursive function, we should put return statement before the function. is it must to put the return statement/necessary??.
Upvotes: 1
Views: 130
Reputation: 213533
This has nothing to do with recursion. The printf statement is dead code and won't work for the same reason as
int main()
{
return 0;
printf("hello, world");
}
doesn't work. You should get compiler warnings for such code.
Furthermore, your recursive function needs a condition where it stops calling itself, or it will just endlessly spawn new functions until you get a stack overflow.
Upvotes: 2
Reputation: 310940
In the first program there is return statement that exits the function without printing anything. That is the function calls itself recursively and in each recursion it returns control at once to the caller. The comtrol never achieves the print statement.
In fact the function can be rewritten like
void reverse(char *s)
{
if(*s)
{
return reverse(s+1);
}
}
Upvotes: 0