What does unary + do?
I am really confused as to the purpose of the unary + operator. What in the world does it do? I have tested it and it doesn't return the absolute value. Does it just return the operand? And if so what purpose is it?! (I mainly care about integer types)
Labdabeta
Practically a Master Poster
614 posts since Feb 2011
Reputation Points: 27
Solved Threads: 31
Skill Endorsements: 1
thines01
Postaholic
2,433 posts since Oct 2009
Reputation Points: 447
Solved Threads: 408
Skill Endorsements: 7
I kind of like the idea of unary plus being an absolute value sign. Right now, the unary plus is nothing more than extra information to the user. Maybe to hint to the user that it should always be a plus or something. It has no effect.
firstPerson
Industrious Poster
4,044 posts since Dec 2008
Reputation Points: 851
Solved Threads: 625
Skill Endorsements: 15
> It has no effect
For standard types, a unary + always yields an r-value.
unsigned short s = 8 ;
unsigned short& r = s ; // s is an l-value
unsigned short&& rvr = +s ; // +s yiels an r-value
For standard types, a A unary + performs a promotion where applicable.
unsigned short s = 8 ;
auto x = s ; // type of x is unsigned short
auto y = +s ; // type of y is signed int
//(unsigned int if int cannot represent the full range of unsigned short)
char c = 'A' ;
std::cout << c << ' ' << +c << '\n'
For user-defined types, the overloaded unary + operator could do anything one pleases.
#include <iostream>
#include <string>
#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive ;
void foo( const std::string& str, const sregex& re )
{
sregex_iterator iter( str.begin(), str.end(), re ), end ;
for( ; iter != end ; ++iter ) std::cout << '[' << (*iter)[0] << "] " ;
std::cout << '\n' ;
}
int main()
{
std::string str = "abcd1234efgh789ij" ;
foo( str, _d ) ; // prints 7 matches: [1] [2] [3] [4] [7] [8] [9]
foo( str, +_d ) ; // prints 2 matches: [1234] [789]
}
vijayan121
Posting Virtuoso
1,740 posts since Dec 2006
Reputation Points: 1,236
Solved Threads: 320
Skill Endorsements: 11
Means? Absolute value refers to be value having no dependence on its sign right? So what is an absolute value sign?
As in the mathematical sense of absolute value. In mathematics one would use the Bar symbol as in , |x|, using the unary + symbol, as in +x, kind of amused me a little.
firstPerson
Industrious Poster
4,044 posts since Dec 2008
Reputation Points: 851
Solved Threads: 625
Skill Endorsements: 15
Question Answered as of 1 Year Ago by
firstPerson,
PrimePackster,
thines01
and 1 other