Vikash
Vikash

Reputation: 1139

Why the function pointer pointing to different function works than it is defined

In the following program the function pointer is defined to point to a function which accepts no argument and returns int yet the function pointer works here. Why?

#include<stdio.h>

int mul(int*,int*);

int main()
{   int a=10,b=20;
    int(*p)();
    p=&mul;
    printf("%d ", (*p)(&a,&b));
        return 0;
}


int mul(int*a,int*b)
{   
    return (*a * *b);
}

Upvotes: 0

Views: 115

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

In C, int (*p)() means declare a pointer to a function that takes an unspecified number of arguments and return int. Since the number of arguments is unspecified, it is valid to assign pointer to function int mul(int *a, int *b) to variable p.

If you change the declaration to int (*p)(void), which means declaring a pointer to a function that takes no argument and return int, then the compiler is likely to throw a warning about incompatible pointer type. For gcc, a warning is thrown at default level of warning.

As Keith Thompson mentioned in the comment, you should always use prototypes, i.e. declarations that specify the types of the parameters. In this case, it would be:

int (*p)(int*, int*);

Reference

Upvotes: 3

Related Questions