What is meant by this error? Argument of type "void" is incompatible with parameter of type "void (*)(int a)"

Viewed 1015

I am trying to use a function pointer to call another function, but it gives me an error. I don't understand the error.

Here's my code:

#include<stdio.h>
#include<stdlib.h>

void print(void (*ptr)(int));
void printint(int);

int main()
{
    char a;
    int b;
    scanf("%c %d",&a,&b);
    print(printint(b));
    return 0;
} 

void print(void (*ptr)(int a))
{
    ptr(a);
}

void printint(int a)
{
    // printf("executed");
    printf("%d",a);
}

I think I wrongly used the function pointer. Can someone explain how to implement this program in the correct way?

2 Answers

The problem is that print(printint(b)); is calling printint(b) first and then passing its return value (which is void) to print(). Hence the error.

You need to pass the b value to print() in a separate parameter, and then it can pass the value to printint(), eg:

#include <stdio.h>
#include <stdlib.h>

typedef void (*funcptr)(int);

void print(funcptr, int);
void printint(int);

int main()
{
    char a;
    int b;
    scanf("%c %d", &a, &b);
    print(printint, b);
    return 0;
} 

void print(funcptr ptr, int a)
{
    ptr(a);
}

void printint(int a)
{
    // printf("executed");
    printf("%d", a);
}

The type of the expression printint(b) is void, according to the function printint declaration:

void printint(int);

So, instead of passing a function pointer, you are passing void in this call:

print(printint(b));

The function print should be declared like this:

void print( void (*ptr)(int), int );

and called like this:

print( printint, b );

Correspondingly, the function should be defined like this:

void print( void (*ptr)(int ), int a )
{
    ptr(a);
}
Related