Gary Allen
Gary Allen

Reputation: 1390

Warning C26451: Arithmetic overflow (when subtracting two ints)

When performing the following line of code:

int max = 50, min = -30;
double num = rand() % (max - min) - min;

I get the following warning from Visual Studio 2019:

Warning C26451 Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).

I'm not sure how this is applicable, as I am taking the modulus of a double, which will return and integer, and then subtracting another integer from it, before storing it in a double (which I'm fairly certain isn't the problem).

Is this a bug or am I doing something that could result in truncation etc.?

Thanks

Upvotes: 1

Views: 807

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13749

The difference (in both of subtractions) can result in overflow. The overflow may happen if you subtract negative values from positive, or positive values from negative.

For example, if you subtract something negative from a maximum possible value, you'll get an overflow.

As you have wider destination type, it is possible that you intend this wider result to fit this wider type without overflow. This will not happen, unless you cast one of your operands.

I don't think it is practical to do such cast here, as you use % operator, this will not work with double. And anyway it will not handle overflow, just because you cannot have more range here than range of rand().

Apparently if you want to fix the possible overflow of rand(), you'll need std::uniform_int_distribution with your range. This would fix other rand() problems along (thread safety and not good randomness), but would add a bit of complexity as well.

But sure if you always have -30 to 50 range, there's no overflow, and you can treat it as a false warning. If you literally have int max = 50, min = -30; I even see it as a bug of static analysis to emit this warning. Sure static analysis cannot predict the result of rand(), but there's % to truncate it. Maybe use Help > Send Feedback > Report a problem if you care.

Upvotes: 1

Related Questions