1

I am a beginner in C language. Read various SO threads on function pointers. For instance, How does dereferencing of a function pointer happen, Function Pointer - Automatic Dereferencing [duplicate], so I tried to do an experiment of mine.

Couldn't understand why this error is thrown since I am not using the void value anywhere..

#include <stdio.h>
void f(int j) {
    static int i;
    if (j == 1)
        printf("f: i entered this function main()\n");
    else if(j == 2)
        printf("f: i entered this function through pointer to function\n");
    
    void (*recurse)(int);
    recurse = *f; // "f" is a reference; implicitly convert to ptr.
    if (i == 0){
        i++;
        *recurse(2); 
    } else
        return;
}

int main(void)  
{
    f(1);
    return 0;
}

GCC Version is 11.2.0 Compiler flags used include -std=c99 if I modify line 14 to recurse(2) then the program runs smoothly. No error or warning is thrown by the compiler.

$ gcc testing11.c @compilerflags11.2.0.txt -o testing11.exe
testing11.c: In function ‘f’:
testing11.c:14:10: error: void value not ignored as it ought to be
   14 |         *recurse(2);
         |          ^~~~~~~~~~
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Singh
  • 55
  • 1
  • 6
  • Just do `recurse(2);`. Though may I add that 1) doing recursion is a very bad idea in general and 2) doing recursion through a function pointer is an incredibly bad idea. This function might not have been possible to tail call optimize in the first place, but by making the call through a function pointer you have almost certainly blocked all optimization. For what purpose? – Lundin Jan 18 '22 at 15:25
  • @Lundin As I wrote, `recurse(2)` is working. Thank you for pointing out the recursive function implemented through function pinter being a bottleneck for optimization. Would learn more about the same. (At the moment, I understand little about compilation process and optimization) – Singh Jan 18 '22 at 15:36
  • 1
    There barely exists any scenario in the real world when recursion should be used in C. So if you don't understand how machine code is generated from C source, then I strongly advise against using recursion. – Lundin Jan 18 '22 at 15:37

1 Answers1

2

This expression statement

*recurse(2); 

is equivalent to

*( recurse(2) ); 

So as the return type of the function is void then you are trying to dereference the type void.

It seems you mean

( *recurse )(2); 

Or you could just write

recurse(2); 

because the expression *recurse used in the first call will be again implicitly converted to a function pointer.

So though this call for example

( ******recurse )(2); 

is correct nevertheless dereferencing the pointer expressions are redundant.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335