5 ms·
I used to use the comma operator to return a status code in the same line as an operation, but for some reason nobody liked my style. if (error_condition)
by projektfu 3y ago
I used to use the comma operator to return a status code in the same line as an operation, but for some reason nobody liked my style.
if (error_condition)
return *result=0, ERR_CODE;
So, back to writing lots of statements.
- enriquto 3y agoI love this style (avoiding multiple-statement blocks) ! Sometimes you can still avoid multiple statements by rearranging your code otherwise. For example, in your case, you can set *result=0 at the beginning of the function. Other times, you can also cram the assignment inside the condition using short circuit evaluation; this trick somehow seems more palatable to normies than the comma operator.
- projektfu 3y agoYeah, I felt that in cases (like when doing COM programming) where the true result is almost always returned in a parameter and the status code as the return value, it made a lot of sense to me to combine those into one line wherever they appeared. But, like the article says, this is a lesser-known operator. In libc style, a similar thing makes sense, e.g. return errno=ENOENT, (FILE*)0; I don't know if anyone uses this style. In K&R, they say that it's mostly used in for loops, such as for (i = 0, j = strlen(s) - 1; i < j; i++, j--) ... So that is where I use it now.
- gpderetta 3y agoI have used it c++ to take a scoped lock without naming it and returning a mutex protected value: return scoped_lock{foo_mux_}, return foo_; Also nobody likes it.
- _kst_ 3y agoI think you mean: return scoped_lock{foo_mux_}, foo_;
- gpderetta 3y agoIndeed! :)
- Joker_vD 3y agoDeosn't such an unnamed variable get's immediately destructed, right at the comma? I am pretty certain I'd hit exactly that problem and had to switch to __LINE__-macro to name such scoped locks.
- folmar 3y agoMy understanding of the standard is that the `full-expression` ends at the semicolon and 6.7.7.8 prescribes that the temporary shall be destructed after copying the value to be returned.