Home > Back-end >  How to recursively call a function that has a void function as a parameter in C?
How to recursively call a function that has a void function as a parameter in C?

Time:11-01

I am a beginner in C and I wanted to use a void function that has a void function as a passed argument, and then I wanted to call it in a recursive way. For example void inOrder (struct node *root, void (*f) (struct node *i)) But apparently, I can't use it because the argument has no return type. Does anyone have any suggestions on how to call it recursively? Thank you!

CodePudding user response:

The code shown in a comment, void inOrder (root->leftChild, (*f) (root->leftChild)) has two errors:

  • void should not be present. When calling a function, we simply write its name followed by the arguments in parentheses. We do not declare its type.
  • The expression inOrder (root->leftChild, (*f) (root->leftChild)) attempts to call f. The second parameter of inOrder is a pointer to a function, so pass a pointer to a function, which is just f:
inOrder(root->leftChild, f)

Also note that you are not calling f recursively. f does not call f, directly or indirectly. inOrder may call itself, and hence it recurses, but it just calls f simply, not recursively.

  • Related