STM32 MDK C fallibility

1, MDK compiler negative single byte -1, -2, -3 ... ... process: storage, type conversion, bit alignment.

Char variable defined in the conversion operation process in particular, the type of logic is less than a large treatment as unsigned char, where it is prone to error, to avoid such errors, and the best one-byte signed variable declaration explicitly signed char

char varbyte = -5;
if(varbyte > -2) printf("varbyte > -2 \r\n");
else printf("varbyte < -2 \r\n");

Output Results: varbyte > - 2

// output is varbyte> -2, that is to say -5> -2 This is clearly calculation error.
// Because of the constant -5 during operation is of type int varbyte = -5 At this time will first turn into type int
 // 251 (256-5 = 251), then a ratio of size 251 and -2, 251> - 2, the output varbyte> -2;


// If explicit statement unsigned char varbyte = -5; expected result
 // Signed char varbyte = -5; 4-byte aligned will turn int -5, -5> -2 is not satisfied 

Signed char varbyte = - . 5 ;
 IF (varbyte> - 2 ) the printf ( " varbyte> -2 \ R & lt \ n- " );
 the else the printf ( " varbyte <-2 \ R & lt \ n- " );

Output Results: varbyte <- 2

 

2, the operation priority, left <<, >> is a right shift below +, -, *, /
unsigned char Result = 2 << 3 + 2 ;
 // Result = 32 instead of 10
 @ + << precedence, is calculated << 2 (3 + 2) th power of 2 5 = 32

 

 

 
 

Guess you like

Origin www.cnblogs.com/laosuning/p/12156361.html
Recommended