C language traps-type conversion and C language traps
The following example is taken from an in-depth understanding of computer systems.
Consider the following C language code:
1 #include<stdio.h> 2 3 typedef unsigned char* byte_pointer; 4 5 void show_bytes(byte_pointer pointer, int size){ 6 int i = 0; 7 for (i = 0; i < size; ++i){ 8 printf("%.2x", pointer[i]); 9 }10 }11 12 int main(){13 short sx = -12345;14 unsigned uy = sx;15 printf("uy = %u:\t", uy);16 show_bytes((byte_pointer)&uy, sizeof(unsigned));17 printf("\n");18 }
The program will generate the following output on the machine of the Small-end method: uy = 4294954951: c7cfffff
This indicates that when short is converted to unsigned, we first change the size, and then complete the conversion from signed to unsigned. That is to say, (unsigned) sx is equivalent to (unsigned) (int) sx, and the value is 4294954951, instead of (unsigned) (unsigned short) sx. The latter is 53191. In fact, this rule is required by C language standards.
In addition, when performing an operation, if one of its operations is signed and the other is unsigned, then, the C language implicitly converts the type of the signed parameter to the unsigned parameter and assumes that both numbers are non-negative. This method is not significantly different from standard arithmetic operations, but for Relational operators such as <and>, it will lead to non-intuitive results.
For example, if we evaluate the expression (-1 <0U), the result is 0. Because the second operation number is unsigned, the first operation number is implicitly converted to the unsigned one, so the expression is equivalent to (4294967295U <0U ), this answer is obviously wrong.
For the same reason, let's consider the Code:
1 double sum_elements(double a[], unsigned length){2 int i;3 double result = 0;4 for (i = 0; i <= length - 1; ++i){5 result += a[i];6 }7 return result;8 }
When the input length is 0, an out-of-bounds error occurs.