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)

A single +, it just tells the compiler that it is a positive value.

+3 means 3 is positive, thats all
Well about usage of +, there is short hand methods in C++, Like this; d+=5 Here it means d=d+5.
But since it uses 2 operands, its no longer unary operator (Just mentioned, so that you don't get confused with all these usages).

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.

I kind of like the idea of unary plus being an absolute value sign.

Means? Absolute value refers to be value having no dependence on its sign right? So what is an absolute value sign?

> 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]
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.