I have a doubt from the below 2 code snippets.
I ran this code on 64-bit machine (x86_64-linux-gnu). I can see the value 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 the value
Val
get promoted to high data type when the data type is unsigned char?- If yes, why did not it get promoted from 32-bit to 64-bit
unsigned long
?
Simply put, overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable. If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.
An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).
Integer Overflow occurs when we attempt to store a value greater than the data type's largest value. Similarly, Integer Underflow occurs when we attempt to store a value that is less than the least value of the data type.
Overflow occurs when the magnitude of a number exceeds the range allowed by the size of the bit field. The sum of two identically-signed numbers may very well exceed the range of the bit field of those two numbers, and so in this case overflow is a possibility.
The C11 standard says the following (C11 6.3.11p2.2):
If an
int
can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to anint
; otherwise, it is converted to anunsigned int
. These are called the integer promotions. All other types are unchanged by the integer promotions.
Thus:
unsigned char
will be promoted - however it is an implementation detail whether int
can represent all values of unsigned char
- so it might be promoted to an unsigned int
on those platforms. Yours is not one of those platforms, thus your second comparison is (int)Val + 16 < (int)Val2
.
as the last sentence of the quoted paragraph tells, an unsigned int
is never promoted. Since the arithmetic is done on unsigned ints in the first fragment, the result of 0xFFFFFFFF - 15 + 16
is 0U
on a computer with 32-value-bit unsigned int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With