I am writing a function that just looks up values inside of a table. Is it possible to call that function inside of itself? I've seen stuff about this
and self
and don't really understand it.
Yes, you can. It's called recursion.
void foo(){
foo(); //This is legal.
}
Of course you need to return from it to avoid infinite recursive calls. Failing to return will cause a stack overflow. Here's a better example:
void foo(int n){
if (n == 0)
return;
foo(--n);
}
See Recursion (computer science) (Wikipedia).
An example of calling a function inside a function:
# include<stdio.h>
int factorial(unsigned int number)
{
if (number <= 1)
return 1;
return number * factorial(number - 1);
}
void main()
{
int x = 5;
printf("factorial of %d is %d",x,factorial(x));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With