Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ What is this usage of the + operator called? and what is the purpose?

I recently saw an example in an operator overloading review where they talked about how the + operator was essentially a function with 2 parameters.

With a bit of poking I decided to look at this a bit deeper and found that calling + like a function does indeed work, just not how you would expect... eg:

int first = 6;
int second = 9;
int result = +(second,first);//result=6

The assembly for this is

int result = +(second,first);
mov         eax,dword ptr [first]  
mov         dword ptr [result],eax 

The call to + is simply moving the last parameter into eax.

Can anyone tell me the purpose of this and/or what it is called?

like image 679
jhbh Avatar asked Apr 21 '15 03:04

jhbh


1 Answers

There are two parts to the expression +(second,first) - and neither of them is a function call.

The expression (second, first) uses the rare comma operator, which evaluates each expression in turn and the result of the expression is the last expression evaluated.

The + in this case is just a unary + operator, like saying +5 or -8. So the result of your expression is 6, the value of first.

You can, however, call the operator + like this:

int result = operator +(second, first);
like image 132
Greg Hewgill Avatar answered Oct 01 '22 19:10

Greg Hewgill