I am trying to implement a simple swap function using function pointer but when I assign function's address to a function pointer am getting pointersTofunctionB.c:14:6:warning: assignment from incompatible pointer type [enabled by default]
. Below is my code
#include <stdio.h>
void intSwap(int *a,int *b);
void charSwap(char *a,char *b);
void (*swap)(void*,void*);
int main(int argc, char const *argv[])
{
int a=20,b=15;
char c='j',d='H';
swap=&intSwap;// warning here
swap(&a,&b);
printf("%d %d\n",a,b);
swap=&charSwap;// warning here also
swap(&c,&d);
printf("%c %c\n",c,d );
return 0;
}
void intSwap(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
void charSwap(char *a,char *b)
{
char temp;
temp=*a;
*a=*b;
*b=temp;
}
how do I remove this warning. somebody help me on this.
You need to change
to
Same goes for
swap=&charSwap;
also.Again, your function signature(s) does not match the function pointer signature.
Your function is
which is of return type void, two input parameters of
int *
, whereas, your function pointer signature iswhich takes two
void *
s. Same forvoid charSwap
function also.Either yoou have to change the function signature, or you have to use a different function pointer prototype. Otherwise, the behaviour is undefined. [as mentioned in Vlad's answer].
To remove the warning, code this overload:
The warnings appear due to the following quote from the C Standard
6.3.2.3 Pointers
That two functions would be compatible their parameters shall have compatible types
6.7.6.3 Function declarators (including prototypes)
In your functions parameters are declared as pointers. So that they (pointers) would be compatible they shall be pointers to compatible types
6.7.6.1 Pointer declarators
2 For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.
However types int or char on the one hand and type void on the other hand are not compatible types.
You could define your functions the following way