Jan 8, 2013 at 3:00pm Jan 8, 2013 at 3:00pm UTC
In fact these two functions are equivalent. There is no need to specify the second return in the last function.
Jan 8, 2013 at 3:06pm Jan 8, 2013 at 3:06pm UTC
So there isn't any diffrence between these two codes.Is there?
how about other recursive functions?
for example fibonacci or factorial?
Last edited on Jan 8, 2013 at 3:06pm Jan 8, 2013 at 3:06pm UTC
Jan 8, 2013 at 3:08pm Jan 8, 2013 at 3:08pm UTC
It's a void function. You don't need to use return at all. In your first example return used to end function prematurely. Your second example actually will never execute cout<<reverse_str[i];
routine, so it won't work at all.
Jan 8, 2013 at 3:19pm Jan 8, 2013 at 3:19pm UTC
You exit the function with the return statement
return sting_reverse(reverse_str,size,i+1);
So the next statement will not be executed.
cout<<reverse_str[i];
Jan 8, 2013 at 3:21pm Jan 8, 2013 at 3:21pm UTC
You could write
return ( void ) ( sting_reverse(reverse_str,size,i+1),
cout<<reverse_str[i] );
Last edited on Jan 8, 2013 at 3:29pm Jan 8, 2013 at 3:29pm UTC
Jan 8, 2013 at 3:33pm Jan 8, 2013 at 3:33pm UTC
I made in my code snip a typo that I updated already. Should be either
return ( void ) ( sting_reverse(reverse_str,size,i+1), cout<<reverse_str[i] );
or
return void ( ( sting_reverse(reverse_str,size,i+1), cout<<reverse_str[i] ) );
The difference between my code and your code is that I have one return statement while you have two statements: the first one is the return statement and the second one is the expression statement. The expression statement will not be executed because the control exits the function.
Last edited on Jan 8, 2013 at 3:34pm Jan 8, 2013 at 3:34pm UTC
Jan 8, 2013 at 3:38pm Jan 8, 2013 at 3:38pm UTC
I think that understood... .
thank you ...
Jan 8, 2013 at 3:49pm Jan 8, 2013 at 3:49pm UTC
You could write the function simpler
1 2 3 4
void string_reverse( const char *s )
{
if ( *s ) return ( void ( ( string_reverse( s + 1 ), std::cout << *s ) ) );
}
or as
1 2 3 4
void string_reverse( const char *s )
{
if ( *s ) string_reverse( s + 1 ), std::cout << *s;
}
Last edited on Jan 8, 2013 at 3:51pm Jan 8, 2013 at 3:51pm UTC