Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C(++) short subtracting short = int? [duplicate]

Tags:

c++

types

int

short

Have the following code:

short a = 5;
short b = 15;
short c = 25;

short d = std::min(a, b);
short e = std::min(a, b-c); // Error

The last line cannot be compiled, claiming that there's no overload of min() that matches the arguments "short, int".

What is the reason for this being the case? I understand that the result of b-c could potentially not fit in a short anymore. However that would be the same if I were using INTs and there it doesn't automatically form a LONG or anything to enforce that it fits.

As long as I am sure that the resulting number will never exceed the range of SHORT, it is safe if I use static_cast<short>(b-c), right?

Huge thanks!

like image 248
DragonGamer Avatar asked Dec 20 '25 19:12

DragonGamer


1 Answers

Reason: integer promotion. If a type is narrower than int, it is promoted to int automatically. This makes little difference for signed numbers because overflow is undefined, but for unsigned numbers for which overflow wraps, this allows the compiler to emit a lot less code for most processors.

Most of the time, this automatically casts back because assigning to a narrower variable is not an error. You happened to find a case where this really does cause an issue though.

If you're sure it fits, just cast it back.

like image 92
Joshua Avatar answered Dec 23 '25 07:12

Joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!