-1
const int IX(int x, int y, std::size_t width)
{
    if ((width * y + x) > 0)
    {
        return width * y + x;
    }
    else
    {
        return 0;
    }
}
const int IX(int x, int y, std::size_t width)
{
    int value = width * y + x;
    if (value > 0)
    {
        return value;
    }
    else
    {
        return 0;
    }
}

In here if x=0 and y=-1 independent of width the first function returns the first branch (why?), and the second one returns what is expected. Is this a compiler bug, or am i missing something? Im using visual studio 2019 compiler.

Primemaster
  • 312
  • 5
  • 16

1 Answers1

2

This is a prime showcase of a push to get rid of unsigned types except for very narrow domains (i.e. bit manipulations).

In your first function, where you check the value directly in the branch,

(width * y)

Given that width is unsigned (size_t) the result of this is also unsigned (in your case, quite large value), and as such, is going to be always be greater or equal to zero.

In your second function, you take an unsigned value and than put it back into signed:

int i = width * y

As a result, it becomes signed again, and now becomes less than 0.

Try turning on compiler warnings and you will see a lot of them.

SergeyA
  • 61,605
  • 5
  • 78
  • 137