[Solved] Define sign ambiguous pointer parameter for a function


With C, you have limited options. You can do the typecasting that you don’t like when you call the function:

void MyFunction(unsigned char* Var);

int main(void) {
    unsigned char Var1 = 5U;
    signed char Var2 = 5;

    MyFunction(&Var1);
    MyFunction((unsigned char *)&Var2);
}

you can use void * and typecast in the function itself and just not pass the wrong type of pointer to it:

void MyFunction(void* Var);

int main(void) {
    unsigned char Var1 = 5U;
    signed char Var2 = 5;

    MyFunction(&Var1);
    MyFunction(&Var2);
}

Or if you really want something beyond that, you can use a _Generic macro to automagically typecast it for you. It may or may not be the “best” approach, but I think it will accomplish your goal.

#define MY_FUNCTION_HELPER(X) MyFunction( _Generic((X), \
   char *: (unsigned char *)X, \
   signed char *: (unsigned char *)X, \
   unsigned char *: X \
   ) \
)

void MyFunction(unsigned char *Var);

int main(void) {
    unsigned char Var1 = 5U;
    signed char Var2 = 5;

    MY_FUNCTION_HELPER(&Var1);
    MY_FUNCTION_HELPER(&Var2);
}

The last one works by using the C11-introduced _Generic which allows a form of polymorphism to use different expressions based on the type of a controlling expression. In this case, if X is char * or signed char *, it will perform a typecast to unsigned char *. If X is already unsigned char *, it will remain as such. If X is anything else, it will fail to compile as no other types are accounted for in the generic association list.

1

solved Define sign ambiguous pointer parameter for a function