5

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?
2
  • 8
    This isn't the 90's - a return type on main is required nowadays. Commented Apr 24, 2017 at 14:29
  • When doing arithmetic, everything is promoted to int if can fit, or to unsigned int if cannot. The size of these types is specific to your compiler and you can easily find it out. Commented Apr 24, 2017 at 14:30

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.