### function that call themselves???

Hi again i. Read in the documentation
What exactly it mean call themselves
I tried to explore this in google and still dont get it
And also the prototype function
I want to mention again c++ is my first expirience
With programming so my questions might seem a bit
Obvious to guys with expirience
It means recursion. For example that to calculate the length of a string you can write the following function

 1234 size_t length( const char *s ) { return ( *s ? 1 + length( ++s ) : 0 ); }
this look like a "regular" function to me
closed account (3qX21hU5)
Notice how it calls itself in the return statement if a certain condition isn't met.

return ( *s ? 1 + length( ++s ) : 0 );

This is what they mean by a function calling itself and is often referred to as recursion
Last edited on
A function that calls itself is recurision.

 1234 viod thismyfunction() { cout << "Hi there."<< endl; thismyfunction(); }

But that was an example. Don't actually test it. God only knows what it would do.

You can have functions that call themselves for a loop effect.
If you read the documentation about recursion it probably showed an example for finding the factorial of a number something like this
 1234 const long long factorial( short n ) { return n > 1 ? n * factorial( --n ) : 1; //calls itself multiple times here }

*edit forgot n *
Last edited on
You guys make beautiful use of the if-else operator here.

Unfortunately... I was only just introduced to that topic today.

Remember kiddos if you aren't speaking in "for dummies" lingo you might as well be speaking in code. :P
Fine let me simplify it
 12345 long long int factorial_function( short int n ) { if( n > 1 ) return( n - 1 ); else return( 1 ); }

Edit its also called a ternary operator.
http://en.wikipedia.org/wiki/%3F:
variable = condition ? if_true : if_false;
as in if the condition is true variable = is_true;
if condition is false variable = is_false;
Last edited on
@giblit

Fine let me simplify it

 12345 long long int factorial_function( short int n ) { if( n > 1 ) return( n - 1 ); else return( 1 ); }

You simplified the function such a way that it has nothing common with the calculation of factorial because it always returns 1.:)

So if to continue your simplification the function can be written simply as

 1234 long long int factorial_function( short int ) { return( 1 ); }
Last edited on
whoops I meant n * factorial( n - 1 )...sorry
 12345 long long int factorial_function( short int n ) { if( n > 1 ) return( n * factorial( n - 1 ) ); return( 1 ); }

Topic archived. No new replies allowed.