What is the purpose of a unary “+” before a call to std::numeric_limits<unsigned char> members?

  • A+
Category:Languages

source

#include <limits> #include <iostream>  int main()  {     std::cout << "type/tlowest()/tmin()/t/tmax()/n/n";      std::cout << "uchar/t"               << +std::numeric_limits<unsigned char>::lowest() << '/t' << '/t'               << +std::numeric_limits<unsigned char>::min() << '/t' << '/t'               << +std::numeric_limits<unsigned char>::max() << '/n';     std::cout << "int/t"               << std::numeric_limits<int>::lowest() << '/t'               << std::numeric_limits<int>::min() << '/t'               << std::numeric_limits<int>::max() << '/n';     std::cout << "float/t"               << std::numeric_limits<float>::lowest() << '/t'               << std::numeric_limits<float>::min() << '/t'               << std::numeric_limits<float>::max() << '/n';     std::cout << "double/t"               << std::numeric_limits<double>::lowest() << '/t'               << std::numeric_limits<double>::min() << '/t'               << std::numeric_limits<double>::max() << '/n'; } 

I don't understand the "+" operator in

<< +std::numeric_limits<unsigned char>::lowest() 

I have tested it, replaced it with "-", and that also worked. What is the use of such a "+" operator?

 


The output operator << when being passed a char (signed or unsigned) will write it as a character.

Those function will return values of type unsigned char. And as noted above that will print the characters those values represent in the current encoding, not their integer values.

The + operator converts the unsigned char returned by those functions to an int through integer promotion. Which means the integer values will be printed instead.

An expression like +std::numeric_limits<unsigned char>::lowest() is essentially equal to static_cast<int>(std::numeric_limits<unsigned char>::lowest()).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: