i try to initializing an array of function pointers and i have "warning":
ring-buffer.c:57:19: warning: assignment from incompatible pointer type [enabled by default]
RBufP->rbfunc[0] = &RBufPush;
^
but the neighborhood's ok:
/*typedef for func pointer*/
typedef RBRetCod_t (*RBFunc)();
/*RBufP*/
typedef struct {
RBufSiz_t size; /*size and mask*/
RBufDat_t rbufdat;
RBufPoint_t head, tail;
RBFunc rbfunc[3]; /*announce of function pointers array*/
} RBuf_t;
RBuf_t *RBufP;
...
/*init for func pointers array*/
RBufP->rbfunc[2] = &RBufDel; /*it is ok*/
RBufP->rbfunc[1] = &RBufPull; /*it is ok*/
RBufP->rbfunc[0] = &RBufPush; /*it is bad, why???*/
...
/*body of the functions*/
RBRetCod_t RBufPull(unsigned char *dat)
{
return RBSUCC;
}
RBRetCod_t RBufDel(void)
{
return RBSUCC;
}
RBRetCod_t RBufPush(unsigned char dat)
{
return RBSUCC;
}
please explain to me why the warning occurs in this line: RBufP->rbfunc[0] = &RBufPush;, but in adjacent rows are not there?
See C11 section 6.7.6.3 §14, specifying when 2 function types shall be considered compatible:
[...] If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions. [...]
This is the case for RBufPull and RBufDel, but not RBufPush as unsigned char gets promoted to int.
If you called RBuPush through a pointer of type RBFunc, an int argument would get pushed to the stack, whereas RBufPush would expect an unsigned char. Depending on calling convention and endianness, you'll get incorrect results.
One solution is to change RBufPush to take an int argument. Another one is to use a cast, ie
RBufP->rbfunc[0] = (RBFunc)&RBufPush;
You'll need to cast back to the correct type RBRetCod_t (*)(unsigned char) before calling rbfunc[0].
From ISO/IEC:9899:
J.5.7 Function pointer casts
1 A pointer to an object or to void may be cast to a pointer to a function, allowing data to
be invoked as a function (6.5.4).
2 A pointer to a function may be cast to a pointer to an object or to void, allowing a
function to be inspected or modified (for example, by a debugger) (6.5.4).
But this rule is limited through:
6.3.2.3 Pointers
[...]
8 A pointer to a function of one type may be converted to a pointer to a function of another
type and back again; the result shall compare equal to the original pointer. If a converted
pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
So you are trying to acces different functions with the same Pointerobject type.
This is undefined behavior and the warning therefor is correct.
Note:
What it seems to me, what you try to achieve would be something like an interface in C#.
But this kind of functionallity is not available in C
Related
in the following example I make a CAST of a function without arguments in a pointer to a function that should receive an argument. Assuming that it gives the desired result, is it possible that this procedure causes some malfunction?
online test: https://onlinegdb.com/SJ6QzzOKI
typedef void (*Callback)(const char*);
Callback cb;
void inserisce_cb(void* c) {
cb=c;
}
void esegue_cb(){
cb("pippo");
}
void scriveTitolo(const char* titolo) {
Uart_Println(titolo);
}
void scriveTitolo2() {
Uart_Println("pluto");
}
void main(){
inserisce_cb(scriveTitolo);
esegue_cb();
inserisce_cb(scriveTitolo2);
esegue_cb();
}
Converting a pointer to a function to another pointer to a function is defined by the c standard, but using the resulting pointer to call a function with an incompatible type is not, per C 6.3.2.3 8:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.
The declaration void scriveTitolo2() { … } defines a function that does not have a parameter type list (it uses the old C style of an identifier list, with that list being empty) and that takes no arguments. A Callback pointer points to a function that has a parameter type list and takes a const char * argument. These are incompatible per C 2018 6.7.6.3 15:
For two function types to be compatible,… If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters,…
Since they do not agree in the number of parameters, they are incompatible.
The above speaks only to the issue of converting from void (*)() to void (*){const char *) and using the result to call the function. There is a separate issue in that the function pointer is passed to inserisce_cb, which takes an argument of type void *, which is a pointer to an object type. The C standard does not define the behavior of converting a pointer to a function type to a pointer to an object type. To remedy this, inserisce_cb should be declared to take a pointer to a function type, such as void inserisce_cb(Callback c).
If scriveTitolo2 can be changed, then the compatibility issue can be resolved by changing it to take a const char * parameter that is unused, changing its definition to void scriveTitolo2(const char *).
(Note that it is preferable to declare scriveTitolo2 with the modern C style, as void scriveTitolo2(void) { … }, rather than without the void. This is unrelated to the question, as it would not make the function types compatible, but this format of declaration provides more information to the compiler in many circumstances.)
Additional thoughts to Eric's answer, which holds true for C99 as well:
If you call a function with an argument list not compatible to the function's parameter list, this is according to C99 §6.5.2.2 (6) undefined behavior.
It may work, depending on your compiler's ABI. There are compilers that let the called function clean up the stack, other compilers let the caller clean up. The former case will most likely crash, the latter ... who knows.
You can declare your scriveTitolo2 with an ignored parameter:
void scriveTitolo2(const char*) {
/* ... */
}
And everyone is happy: you and the compiler.
Both of these tests don't give me errors when I compile them yet they are returning different types of pointers.
void *testone(void *x)
{
return (x);
}
void *testtwo(void *x)
{
char *y;
return (y);
}
This is particularly confusing because I am trying to recreate the memcpy function and I can't tell if I should return a void pointer, or an unsigned char pointer.
In C, any object pointer type can be converted to void *, and void * can be converted to any object pointer type without any cast.
Your code obeys those rules; it is OK. The compiler should not complain.
ISO/IEC 9899:2011 §6.3.2.3 Pointers:
¶1 A pointer to void may be converted to or from a pointer to any object type. A pointer to
any object type may be converted to a pointer to void and back again; the result shall
compare equal to the original pointer.
Note that 'object' excludes functions — function pointers have separate rules:
¶8 A pointer to a function of one type may be converted to a pointer to a function of another
type and back again; the result shall compare equal to the original pointer. If a converted
pointer is used to call a function whose type is not compatible with the referenced type,
the behavior is undefined.
I have a generic set of elements provided as a library.
/** Type for defining the set */
typedef struct Set_t *Set;
/** Element data type for set container */
typedef void* SetElement;
/** Type of function for copying an element of the set */
typedef SetElement(*copySetElements)(SetElement);
To create the set I must provide a pointer to a function that handles the copying of elements that I intend to use the set for.
Set setCreate(copySetElements copyElement);
I wrote the following type and copy function:
typedef struct location_t {
char *name;
} *Location;
Location locationCopy(Location location){
Location new_location = locationCreate(location->name);
return new_location;
}
*Obviously I simplified everything to focus the discussion.
When I call:
Set locations = setCreate(locationCopy);
I get a compiler errors:
warning: passing argument 1 of ‘setCreate’ from incompatible pointer
type
expected ‘copySetElements’ but argument is of type ‘struct location_t
* (*)(struct location_t *)’
Your example can be boiled down to
typedef void * (*VF)(void *);
typedef int * (*IF)(int *);
IF a = 0;
VF b = a; //Warning
In the C standard pointers to functions are less versatile than pointer to objects.
You can convert a pointer to an object to a pointer to void (and back) without any cast (and warnings) because there is clause in the standard that explicitly allows for it
A pointer to void may be converted to or from a pointer to any object type.
A pointer to
any object type may be converted to a pointer to void and back again;
the result shall
compare equal to the original pointer.
Note here that a function is not an object.
Regarding pointers to functions the only thing that the standard guarantees is:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.
If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined
Later the standard clarifies what does it mean for two functions to be compatible:
For two function types to be compatible, both shall specify compatible return types.
Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.
Now you may think that void* and struct location_t* are compatible types, after all you can assign each others.
But the standard is crystal clear:
Two types have compatible type if their types are the same.
It later goes on with extending this relationship for more complex types and qualified types.
It may sound surprising but int* and void* are not compatible.
They can be assigned but are not compatible, after all the void* could point to a float or an object with different alignment requirements.
When it comes to pointers of different types the standard is concerned mostly about assigning them back and forth.
It doesn't forbid converting between incompatible pointer types, but using them is undefined behavior, hence the warning.
The better approach is to perform the cast inside the function, as suggested in this answer.
All your function should have signature void* (void*) so that no cast between pointers to functions is needed.
SetElement locationCopy(SetElement element)
{
Location location = (Location)element;
Location new_location = locationCreate(location->name);
return new_location;
}
The casts inside the functions are again subject to undefined behavior if the SetElement pointers are cast to incompatible pointers but that shouldn't happen if you'll call locationCopy only with pointers to Locations (as you indeed expect to do).
As a side note, some programmer may frown upon using a typedef to hide a pointer type.
I've seen some examples of array of function-pointers (here, for example)
In the examples I've seen the array holds functions that have a return value of the same type (all int's, or all void's for example).
But I'm wondering can you have an array that holds function-pointers of different types?
The next code won't compile:
#include <stdio.h>
void Empty_Funcion()
{
;
}
int funcAdd(int a, int b){
return a+b;
}
int main()
{
int ret = 0;
void *array[5] = {&Empty_Funcion, &funcAdd, &Empty_Funcion, &funcAdd, &Empty_Funcion};
ret = (*array[1])(5,7);
printf("%d\n", ret);
return 0;
}
It says the problem is with the assignment ret =... "void value not ignored as it ought to be".
You can do it like this:
ret = ( ( int (*)(int,int) ) array[1] )(5,7);
You need to cast to pointer to function type with the correct signature.
But I'm wondering can you have an array that holds function-pointers of different types?
As noted in Anatoly's answer, your code doesn't work because your array intends to declare contain pointers-to-functions that return void, but then you try invoking it as a pointer-to-function that returns int. These are incompatible types, so an explicit cast is required. And, as noted in section 6.3.2.3/8 of the ISO C99 standard, casting a function pointer to a different function pointer type and back again is permitted:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
That said, I don't see any point to doing this. The function pointer cast is a static cast (a cast known to the compiler) and not a dynamic cast, so you must manually keep track of which elements in your array are of type void (*)() and which are of type int (*)(int, int). It'd instead be simpler to have a separate array for each function pointer type and avoid casting altogether. Doing so would be less error-prone since you would not risk invoking a function pointer as the wrong type (which would be undefined behavior).
Update:
You've changed your question so that array is now an array of void* pointers. Note that although normal pointers may be freely cast to and from void*, this is not true for function pointers (although it is considered to be a common extension in many implementations).
Your array is not declared as an array of function pointers, it is declared as an array of pointers to void.
To declare the array as an array of function pointers you can do:
int (*)(int,int) array[5] = ...
or for clarity:
typedef int (*my_function_pointer_type)(int,int);
my_function_pointer_type array[5] = ...
In theory, you cannot call a function which returns void and expect it to return something. This is against the C standard. In practice, if you do this you most likely get an unpredictable value, but in some cases (such as trying to return a structure) with some ABIs you can get a crash.
The best way is to match the type of your "dummy" function to the type of other functions being put into the array.
typedef void* ListElement;
typedef int(*CompareListElements)(ListElement, ListElement);
ListResult listSort(List list, CompareListElements compareElement) {
.
.
.
qsort(arr, size, sizeof(*arr), compareElement);
.
.
.
}
The first two lines are to clarify what is the CompareListElements.
When I send compareElement as an argument to the library function 'qsort' I receive these warning messages:
passing argument 4 of 'qsort' from incompatible pointer type [enabled by default]
How can I solve this problem?
Avoid undefined behaviour
Rewrite the comparator so it matches what qsort() expects:
typedef int (*CompareListElements)(const void *, const void *);
And inside the comparator, do the conversion to the correct type:
int compare_elements(const void *v1, const void *v2)
{
const RealType *p1 = v1;
const RealType *p2 = v2;
…do comparison…
return …;
}
This way, you don't cast the function pointer at all. The RealType is whatever is the type hidden behind the (poorly chosen):
typedef void *ListElement;
The real type is not void; it is probably some structure type. Note that using void * as the list element type loses almost all the type safety that's available with C (which is arguably little enough to begin with). You'd do better with:
typedef struct Element ListElement;
or something like that, and passing pointers to ListElement around. (See also Is it a good idea to typedef pointers?. You may also find How to sort an array of structs in C? helpful, and there are undoubtedly other related questions that will help.).
Why does the cast lead to undefined behaviour?
Note that casting the function pointer leads to undefined behaviour according to the C standard:
C11 §6.3 Conversions — §6.3.2.3 Pointers ¶8
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.
So, while it is permissible to cast a function pointer that doesn't match what qsort() expects, the problem is that qsort() will invoke it as the converted type, and that is not generally compatible with the function's type, so the behaviour is undefined — notwithstanding examples to the contrary published by demigods in the Unix pantheon.
Often, you will get away with it, but the standard says you may not always get away with it. Since the fix is fairly simple, use it; avoid undefined behaviour.