Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unary minus perform integral promotion?

const auto min = -std::numeric_limits<T>::max();
T x = min; // conversion from 'const int' to 'short', possible loss of data

T is a template argument, a short in this case. Unary minus apparently performs integral promotion.

  • Why does unary minus perform integral promotion?
  • If auto is changed to T no warning is generated, but it should be assigning an int to a short. Why isn't there a warning (it could be VS being fancy)?
like image 863
David Avatar asked Aug 02 '12 20:08

David


1 Answers

Short answer: (now long because people want to be excessively pedantic about English which by its very nature is not exact).

Its not explicitly (as in the unary minus mathematical). But as part of any operation (this includes unary minus operation) on POD data there is an implicit check on input parameters (the smallest integer type that can be used in and operation is int) so there is integral promotion on the input before the unary minus (the mathematical part not the operation part). The output of all operations on POD is the same as the input parameters (after integral promotion is applied). Thus here the output is also an int.

Long answer:

In C (and thus C++) the smallest type that POD operations happen on is int. So before the unary minus is applied the value is converted to int. Then the unary minus is applied. The result of the expression is thus int.

See here: Implicit type conversion rules in C++ operators

like image 191
Martin York Avatar answered Sep 23 '22 22:09

Martin York