Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return with assert and comma operator

Tags:

c++

c++17

http://en.cppreference.com/w/cpp/algorithm/clamp gives this as a possible implementation for std::clamp:

template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) {     return assert( !comp(hi, lo) ),         comp(v, lo) ? lo : comp(hi, v) ? hi : v; } 

While I do understand how this works, putting the assert statement in the return seems rather strange to me; I would have written it as:

template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) {     assert( !comp(hi, lo) );     return comp(v, lo) ? lo : comp(hi, v) ? hi : v; } 

Still, I'm guessing they chose their implementation for a reason; is there advantage of their version over "mine"?

like image 870
rainer Avatar asked Apr 05 '17 10:04

rainer


People also ask

What does the comma operator do in syntax?

Syntax. The comma operator separates expressions (which have value) in a way analogous to how the semicolon terminates statements, and sequences of expressions are enclosed in parentheses analogously to how sequences of statements are enclosed in braces: (a, b, c) is a sequence of expressions, separated by commas,...

How do you use a comma in a for loop?

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop. The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

How do you use a comma in a return statement?

The comma can be used in return statements, to assign to a global variable or out parameter (passed by reference). This idiom suggests that the assignments are part of the return, rather than auxiliary assignments in a block that terminates with the actual return. For example, in setting a global error number:

How to overload comma operator in C++?

In C++, we can overload the comma operator using Operator Overloading. For Example: For “ Send the query X to the server Y and put the result in variable Z”, the “and” plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected.


1 Answers

In C++11, constexpr functions could only have a single return statement (see here). The suggested implementation allows the function to be used in a C++11 compliant compiler.

C++14 removed this restriction, so your implementation is also valid in C++14 or later.

Disregarding this, the functions are exactly equivalent, and your one is definitely more readable.

like image 187
Joseph Ireland Avatar answered Sep 19 '22 15:09

Joseph Ireland