Kamal Kumar
Kamal Kumar

Reputation: 91

Data overflow while comparing the values

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?

Upvotes: 5

Views: 332

Answers (2)

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.

Upvotes: 6

JeremyP
JeremyP

Reputation: 86681

Yes, in the second case the numbers are promoted to int. If you modify your code thus:

#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 behaviour you expect.

Upvotes: 2

Related Questions