Question

This code I am looking at has a lot of places where I see things like this happening:

char *functionName(char *passedVariable)
{
    unsigned char *newVariable = (char* ) passedVariable;

Why is this being done? I always try to be consistent in the use of signed/unsigned, because I know that switching between the two can cause problems, but this developer doesn't seem to care.

Was it helpful?

Solution

Changing the pointer type is not really an issue, this address will still be valid. However interpreting the pointed data as signed/unsigned makes a difference if and only if... the signed data is negative. So in your example if your char's are always positive, then it's ok, otherwise it is not.

Example of signed/unsigned casts:

char c = 42;
char d = -42;
unsigned char cu = c;
unsigned char du = d;

printf("c  %d\n", c);
printf("cu %d\n", cu);
printf("d  %d\n", d);
printf("du %d\n", du);

Output:

c  42
cu 42
d  -42
du 214

OTHER TIPS

They might for example be UTF-8 strings, which consist of unsigned bytes and might be desirable to manually process as such, and yet they're safe to pass to printf which on many platforms expects a signed char so you have to cast somewhere to avoid a warning.

For a pointer it doesn't matter, so long as signed and unsigned chars are the same size in memory this is just the address. And unsigned char * makes the most sense for an arbitrary memory address - which is why most purely memory functions take it as an arguemnt

In the case of strings, which your example looks like, it probably doesn't matter. ASCII values only go from 0-127, which means they'll fit in either a signed or an unsigned char without trouble. In addition, the signedness of an undecorated char is implementation defined (hence the existence of the signed keyword). If char were an unsigned type, your example wouldn't have any sign conversions at all.

In general, the type of casting in your example is used to shut up "pointer sign" warnings when working with third party code that uses different coding styles or makes different assumptions about the signedness of char. It's not always possible to stay consistent in such a case, but casting to change the sign of string pointers is unlikely to cause any problems.

The signedness of char is not specified by the C language because a character is not by nature a signed value and, when C was standardized, some implementations treated them as signed and some did not. So, it is always safe to convert char to either signed char or unsigned char. The former isn't common but the latter is in order to use the char as an array index or an argument of the ctype.h is... and to... functions. But without seeing any of the actual code that uses the unsigned char* pointer, it's impossible to be sure why it is being used.

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