Search code examples
cunsignedsigned

What is the deal with assigning an unsigned variable to a signed value?


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.


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