5

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?

jhbh
  • 317
  • 4
  • 11
  • 2
    nice question, I'll put it in the same category with [What is the name of the “-->” operator?](http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator) – vsoftco Apr 21 '15 at 03:08
  • Having seen the answer, I think that is super fair. I feel like a complete idiot. – jhbh Apr 21 '15 at 03:28
  • I was actually not ironic :) It is a fair question and I bet many people are first mislead by this funny form, especially if having some functional programming background. – vsoftco Apr 21 '15 at 03:31

1 Answers1

11

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);
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285