0

What will be the equivalent code in C for the following C++ code?

int main()  
{  
    //... 
    int count=0;  
    fun(++count);  //function call
    //... 
}  
void fun(int &count)  //function definition
{  
    //...  
    fun(++count);  //Recursive Function call
    //... 
}  

Here count variable is used to keep a track on number of calls of fun()

Bittu
  • 33
  • 4
  • 1
    I don't think post-increment works with reference parameters. – Barmar Nov 28 '20 at 17:51
  • 1
    See https://stackoverflow.com/questions/32911353/increment-operator-on-reference-variable – Barmar Nov 28 '20 at 17:51
  • cannot say equivalent, but you can use either `static` variable or a pointer to get the same behavior in `C` – IrAM Nov 28 '20 at 17:52
  • My C++ is rusty. How can you pass an expression by reference? Why would you want to increment `count` once when calling and once in the function if the purpose is to count function calls? – Vercingatorix Nov 28 '20 at 17:53
  • @Mat I am sorry; my code will be `++count` – Bittu Nov 28 '20 at 17:55

1 Answers1

5

You might use pointer:

int main()
{  
    int count = 0;
    ++count;
    fun(&count);  //function call
    // ...
}

void fun(int *count)  //function definition
{
    // ...

    ++*count;
    fun(count);  //Recursive Function call
    // ...
}  
Jarod42
  • 203,559
  • 14
  • 181
  • 302