Home > Software engineering >  Visual Studio C has different comparison results for UINT16 and UINT32
Visual Studio C has different comparison results for UINT16 and UINT32

Time:11-08

I caught myself checking if the difference between two unsigned numbers was >= 0. I ran a test running Visual Studio 2022 Preview with the following code. In both cases the answer was true. That seems right to me as how could an unsigned number be considered negative?

However, when I changed all the types from UINT32 to UINT16 or UINT8, the first comparison returned false. I suppose it is related to the native size. But shouldn't the result be the same regardless of size? (UINT64 seems to behave like UINT32.)

#include <Windows.h>
#include <iostream>
using namespace std;

int main()
{
  UINT32 a = 5;
  UINT32 b = 10;
  UINT32 c = 0;

  if ((a - b) > 0)
  {
    cout << "\nTrue.";
  }
  else
  {
    cout << "\nFalse";
  }

  c = a - b;

  if ((c) > 0)
  {
    cout << "\nTrue.";
  }
  else
  {
    cout << "\nFalse";
  }
}

CodePudding user response:

The issue arises because, when a and b are UINT16 or UINT8 types, they have enter image description here

However, when we change the type to UINT16, we see that the a - b expression is, indeed, evaluated as an int:

enter image description here

  • Related