Question

My default char type is "unsigned char" as set in the gcc option (-funsigned-char gcc). So arguably I can use "char" when I need "unsigned char" in the code. But i am getting warning for conversion between (char*) and (unsigned char* or signed char*):

"error: pointer targets in passing argument 1 of 'test2' differ in signedness" .

How can I avoid warning when I pass unsigned char* variable to char* (knowing that my syetem has default unsigned char as set by compiler option)?

static void test2(char* a)      //char is unsigned by deafult as set by -funsigned-char gcc option
{
}

void    test1(void)
{
        // This passes, but if i change it to unsigned char (or 'signed char') it fails   
        // I dont want it to fail for "unsigned char c" since default char is unsigned.
        char    c = 65; 
        test2(&c);
}
Was it helpful?

Solution

The switches -funsigned-char and -fsigned-char do not refer to char *.

You might use -Wno-pointer-signto switch off the warning you receive.

OTHER TIPS

Use a cast:

char c = 65;   // weird magic :-(

test2((unsigned char *)(&c));

All char types are layout compatible, and casting their pointers does not constitute type punning or violate aliasing rules, so you can do this freely.

The proper solution is to pass the correct type of variable to the function, i.e. if the function expects plain char, then declare a plain char and take its address, and so on.

The C standard says that "char", "signed char", and "unsigned char" are different types. "char" must have the same behaviour as either "signed char", or "unsigned char", as determined by compiler switches, but you can't use them interchangeably. You should be writing code that works exactly the same regardless of whether you use -funsigned-char or not.

The suggestion by another poster to use a cast is not good. All that does is suppress the warning, it would be clearer to explicitly disable the warning (e.g. with a pragma, or turn the warning off globally in your makefile).

The cast doesn't fix the problem with the code, it just stops the compiler pointing it out. This is a slightly academic point, but on a non 2's complement system, signed chars may have trap representations (they are layout compatible for values 0 <= x <= CHAR_MAX but not other values). So the code could crash.

Based on the details you've given, in practical terms your best solution is probably just to disable the warning and live with the fact that the code is non-portable in this respect.

Finally I got an answer :

-Wpointer-sign is implied by -Wall and by -pedantic . To avoid warning use -Wno-pointer-sign

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top