Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to reference the function you are inside of in C?

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.

like image 565
Kyle Hotchkiss Avatar asked Aug 17 '11 23:08

Kyle Hotchkiss


2 Answers

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);
}
like image 165
Heisenbug Avatar answered Sep 28 '22 09:09

Heisenbug


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));
}
like image 26
hari Avatar answered Sep 28 '22 07:09

hari