Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dereferencing function pointer to function returning void throws error: void value not ignored as it ought to be

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ 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);
         |          ^~~~~~~~~~

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading