Don't say much, said all is a burden! Just look at the code!
Copy Code code as follows:
<span style= "font-size:14px" > #include <stdio.h>
int array[] = {23, 34, 12, 17, 204, 99, 16};
#define Total_elements (sizeof (array)/sizeof (array[0))
int main (void)
{
int d =-1, x;
if (d <= (total_elements-2))
{
x = array[d+1];
printf ("D <= total_elements-2\n");
}
Else
{
printf ("The Bug is out!\n");
}
return 0;
}
</SPAN>
Interested can guess what the result is, and then run to see if the results are the same as they think? What is the truth of it?
GCC below the results as follows:
Copy Code code as follows:
<span style= "font-size:14px" >zy@pc:~/workspace/homework/commonfunc$./a.out
The Bug is out!
</SPAN>
Copy Code code as follows:
<span style= "font-size:14px" >
Total_elements </SPAN>
The value defined is the unsigned int type (because the sizeof () return type is unsigned), the IF statement tests equality between signed and unsigned, so the
D upgraded to unsigned (unsigned int) type, the result of the conversion of 1 to unsigned int is a very large positive integer that causes the expression to be false,
So if you want the result to be correct, you have to change the type first.
Copy Code code as follows:
<span style= "font-size:14px" >if (d <= (int) (TOTAL_ELEMENTS-2))
</SPAN>
So that we can get the right results!
(a) The suggestion of no sign;
1 try not to use unsigned types in your code to avoid adding unnecessary complexity, especially because unsigned numbers do not have negative values to represent
2 use a signed type such as int so that you don't have to worry about boundary conditions when it comes to upgrading complex details of mixed types ( -1 translates into very large integers)
3 unsigned numbers are used only when using bit segments and binary masks. You should also use coercion type conversions in an expression so that the operands are either signed or unsigned, so you do not have to select the type of the result by the compiler.