Main content: Compiler type ANSI C and K&r C type judgment, C compiler bug details
#include <stdio.h>int main () {///Example 1: Compiler type judgment/* * K&r uses the unsigned retention principle that when an unsigned type is mixed with ing or a smaller integral type, the result type is unsigned * ANSI c is used Value retention principle, that is, when several integer operands are mixed as follows, the result type may be signed or unsigned *, depending on the relative size of the operand's type */if ( -1 < (unsigned char) 1)//I use the compiler is ANSI C, when written I F ( -1 < (unsigned int) 1), 1 is converted to a large positive number,//and the current expression does not convert, confirming the ANSI C-Value retention principle printf ("-1 is the less than (UN Signed char) 1:ansi semantics\n ") elseprintf ("-1 not less than (unsigned char) 1:k&r semantics\n ");/**************** * Example 2: error Example description * ****************************************************/ int array[] = {1,2,3,4,5,6,7}; #define TOTAL_ELEMENTS (sizeof (array)/sizeof (array[0])) /* using array[0] instead of array[int], you can change the type of array arrays without changing the # define statement (such as turning int into char) */ int d =-1, x; /* (d =-1) <= (7-2 =5) is supposed to print the following statement * But Total_elements returns the unsigned int type (because sizeof () returns the type of * is an unsigned number), if statement in signed int and Unsig When testing equality between Ned Int, * Promote the type of D to unsigned int, 1 to unsigned int as a large positive integer, * This bug exists in ANSI C, and sizeof in K&r C also returns unsigned, to fix this ask Total_elements (d <= (int) total_elements-2) */if (d <= total_elements-2) {x = array[d+1], as long as the forced type conversion of the printf ("x =%d\n", x);} /* Small inspiration: 1, try not to use the unsigned type in your code, especially, not just because the unsigned number does not have a negative value (such as age, national debt) and use it to represent the number 2, try to use a signed type like int, so that when it comes to the complex details of upgrading mixed types, No need to worry about convenience (such as 1 converting to a very large positive number) 3, unsigned numbers can only be used when using bit segments and binary masks. You should use coercion type conversions in expressions so that operands are unsigned or signed, so that you do not have to have a compiler to select the type of result, in the first example, */return 0;}
Output:
Program Ape---C language details 16 (see absolute value, compile type ANSI C and K&r C type judgment, C compiler type conversion bug details)