Data overflow when comparing values

I have a doubt from the code snippets below.

I ran this code on a 64-bit machine (x86_64-linux-gnu). I see that the value of Val overflows when the data type is unsigned integer .

 #include<stdio.h> main() { unsigned int Val = 0xFFFFFFFF-15, Val2 = 0xFFFFFFFF; if (Val+16 < Val2) { printf("Val is less than Val2\n"); } } 

If the data type is unsigned char , it does not overflow.

 #include<stdio.h> main() { unsigned char Val = 0xFF-15, Val2 = 0xFF; if (Val+16 < Val2) { printf("Val is less than Val2\n"); } } 

I have two questions:

  • Does Val increase by a high data type when the data type is unsigned char?
  • If so, why didn’t he get a boost from 32-bit to 64-bit unsigned long ?
+5
source share
2 answers

The C11 standard states the following (C11 6.3.11p2.2):

If int can represent all values ​​of the original type (limited by the width for the bit field), the value is converted to int ; otherwise, it will be converted to unsigned int . They are called whole stocks. All other types are not affected by whole promotions.

In this way:

  • unsigned char will move forward - however, this is an implementation detail if int can represent all unsigned char values ​​- so unsigned int can be assigned on these platforms. You do not have one of these platforms, so your second comparison is (int)Val + 16 < (int)Val2 .

  • as stated in the last sentence of the cited paragraph, unsigned int never progresses. Since arithmetic is performed in unsigned ints in the first fragment, the result 0xFFFFFFFF - 15 + 16 is 0U on a computer with a 32-bit unsigned bit.

+6
source

Yes, in the second case, the numbers increase to int . If you change your code this way:

 #include<stdio.h> int main() { unsigned char Val = 0xFF-15, Val2 = 0xFF; if ((unsigned char)(Val+16) < Val2) { printf("Val is less than Val2\n"); } } 

You will get the expected behavior.

+2
source

Source: https://habr.com/ru/post/1267097/


All Articles