3

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!

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
DragonGamer
  • 834
  • 3
  • 9
  • 27

1 Answers1

3

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.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • "for most processors". That is, for most 16-bit processors. For 8 or 32 bit processors, not so much. And not even optimum for processors that emit a 32 bit result. More a bit of history tied to early implementations. – david Sep 09 '19 at 02:02
  • @david: Actually that's for 32 bit processors. They would otherwise have to emit code to shear off the high bits at several places. – Joshua Sep 09 '19 at 02:05