Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use this comma in this return statement? [duplicate]

Tags:

c++

I understand what this C++ function does, but I don't understand why the return statement is written this way:

int intDivide(int num, int denom){
  return assert(denom!=0), num/denom;
}

There is only one statement here, because there is only one ; but the comma confuses me. Why not write:

int intDivide(int num, int denom){
  assert(denom!=0);
  return num/denom;
}

Aside from "elegance" is there something to be gained in the first version?

What exactly is that comma doing anyway? Does it break a single statement into 2 parts such that essentially the above 2 versions are identical?

like image 805
Jerome Baldridge Avatar asked Dec 25 '16 13:12

Jerome Baldridge


1 Answers

Although the code didn't seem to use constexpr, C++11 constexpr functions were constrained to have only one statement which had to be a return statement. To do the non-functional assertion and return a value there would be no other option than using the comma operator. With C++14 this constraint was removed, though.

I could imagine that the function was rewritten from a macro which originally read something like this

#define INT_DIVIDE(nom,denom) (assert(denom != 0), nom/denom)

The built-in comma operator simply sequences two expressions. The result of the expression is the second operand. The two functions are, indeed, equivalent. Note, that the comma operator can be overloaded. If it is, the expressions are not sequenced and the result is whatever the overload defines.

In practice the comma operator sometimes comes in quite handy. For example, it is quite common to use the comma operator when expanding a parameter pack: in some uses each of the expansions is required to produce a value and to avoid void results messing things up, the comma operator can be used to have a value. For example:

template <typename... T>
void g(T const& arg) {
    std::initializer_list<bool>{ (f(arg), true)... };
}
like image 142
Dietmar Kühl Avatar answered Oct 20 '22 05:10

Dietmar Kühl