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

In this code I'm looking at, there are many places where I see things like this happening:

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

Why is this done? I always try to be consistent in using signed / unsigned because I know that switching between them can cause problems, but this developer does not seem to care.

0
source share
5 answers

Changing the type of the pointer is not really a problem, this address will still be valid. However, interpreting pointy data as signed / unsigned matters if and only if ... the signed data is negative. So, in your example, if your char always positive, then this is normal, otherwise it is not.

Example of signed / unsigned tricks:

 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); 

Conclusion:

 c 42 cu 42 d -42 du 214 
+1
source

They can be, for example, UTF-8 strings, which consist of unsigned bytes and may be desirable to manually process as such, and yet they are safe to pass to printf, which on many platforms expects a signed char, so you need to throw somewhere- Something to avoid a warning.

0
source

In the case of the lines that look in your example, this probably doesn't matter. ASCII values ​​start only from 0-127, which means that they can easily get either signed or unsigned char. In addition, the signature of an unconfirmed char is determined by the implementation (hence the existence of the signed keyword). If char was unsigned, in your example there would be no icon conversions.

In general, the casting type in your example is used to close the "sign pointer" warnings when working with third-party code that uses different coding styles or makes different assumptions about char signing. It is not always possible to remain consistent in this case, but leading to a change in the sign of line pointers is unlikely to cause any problems.

0
source

For the pointer, this does not matter if the signed and unsigned characters have the same size in memory, this is just the address. And unsigned char * makes the most sense for an arbitrary memory address - this is why most pure memory functions take it as an argument

0
source

The char not indicated by the C language, because the character is not a signed value by nature, and when C is standardized, some implementations considered them to be signed, and some did not. This way you can always convert char to signed char or unsigned char . The former is not general, but the latter is to use char as the index of the array or as an argument to the functions ctype.h is... and to... But, without seeing any real code using the unsigned char* pointer, it is impossible to be sure why it is being used.

0
source

All Articles