Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data overflow while comparing the values

Tags:

c

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:

  1. Does the value Val get promoted to high data type when the data type is unsigned char?
  2. If yes, why did not it get promoted from 32-bit to 64-bit unsigned long?
like image 654
Kamal Kumar Avatar asked Apr 24 '17 14:04

Kamal Kumar


People also ask

What is difference between overflow and Underflow?

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.

What happens when integer overflow?

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).

What is overflow and Underflow of data in C?

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.

What happens with overflow?

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.


1 Answers

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 an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

Thus:

  1. 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.

  2. 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.

like image 137