1

My last line in my method was supposed to be

return methodName(xxx,xxx);

but I had it as

return (xxx,xxx);

The method return type is bool and I only noticed the typo when I debug the problem. I did not expect return (xxx,xxx); to compile. What did it do exactly?

msc
  • 33,420
  • 29
  • 119
  • 214
Coffeecake
  • 23
  • 2

3 Answers3

5

Return value of () operator

This is not an invocation of () operator. The syntax of () operator requires the identifier of the function or the variable that is being invoked. Without the identifier, parentheses around the expression are used to group sub-expressions and may change the order in which operations are executed. For example: 1 - (2 - 3) groups the latter two operands and the result is different from 1 - 2 - 3. Here is an example where the parentheses invoke a function: 1 - cos(2 - 3).

In your case there are no sibling expressions so the parentheses do not change the order of anything and the expression is equivalent to

return xxx,xxx;

This is an invocation of comma operator, and is similar to:

xxx;
return xxx;

This is well formed as long as xxx is implicitly convertible to the return type of the function.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • imho "Parentheses around the expression are used to group sub-expressions" does not exactly address the confusion OP had, because the function call operator can also be just parentheses around expressions, as in `methodName(xx,xx);` – 463035818_is_not_an_ai Apr 27 '17 at 10:23
  • @tobi303 I expanded a bit on why this is not an invocation of operator() – eerorika Apr 27 '17 at 10:25
  • thx, btw it wasnt just complaining for the sake of complaining, I didnt know how to phrase it properly while your explanation now sounds reasonable. – 463035818_is_not_an_ai Apr 27 '17 at 11:14
  • @tobi303 it didn't come off as being for the sake of complaining. I found it legitimate constructive criticism and I appreciate it. In fact, I had already thought the same thing and was already writing my edit when you commented. – eerorika Apr 27 '17 at 11:25
0

The comma, operator will return the last element in the provided list.

return (a, b, c) is equal to return c i.e. its returning last element c

Ajay
  • 2,483
  • 2
  • 16
  • 27
0

The method return type is bool is the important point here.

The primary aim of C++ is evaluating expressions and in

return (expression1,expression2);

You have two expressions namely expression1 and expression2 which are evaluated one after the other ( the comma - which is just a separator - does this bit ).

Since expression2 comes last, whatever value it is evaluated to is returned. If expression2 returns a non-zero value the returned value will be true and if not false.


Sidenote: Though , can be overloaded it is pretty clear from the question that you're using it just as a separator

sjsam
  • 21,411
  • 5
  • 55
  • 102