Killing the comma operator

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue May 10 14:52:21 PDT 2016


On 10.05.2016 23:30, Observer wrote:
> I've programmed in C for decades, and in Perl for a decade, and *never*
> had a problem with the comma operator in either language.

Neither have I. It's a cheap claim to make though, and it does not 
really add anything relevant to the discussion.

> While I
> haven't been part of any D-language discussions about this operator,
> I fail to see it as causing serious code problems.
> ...

Lack of proper tuples is a serious enough problem.

>
> Now admittedly, there aren't too many situations where the comma acting
> as a C-type operator finds a use.  But commas in all of the for-loop
> control expressions, not just the increment clause, are definitely useful.
> And more than that, they're useful whenever you want to execute several
> independent calculations in some context that doesn't allow "statement
> expressions".  See http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
> for how this is supported in GNU C, with a very clean syntax.  I would
> strongly suggest that if you want to deprecate the comma operator for
> some reason, that you build statement expressions into the language,

The comma operator does not allow executing statements, but delegates 
can do this even today.

auto var = { stmt1; stmt2; stmt3; return expr; }();

Also, tuples can do everything that comma expressions can.


> allow them in all contexts where comma operators are presently very
> common, and document this widely as a standard idiom in the language.
>
> Note that for-loops are definitely not the only places where comma
> operators come in handy.  As an example, I wrote a very long critique
> of TDPL, and sent it off to Andrei late last year.  In an item for
> page 382, I provided a lot of replacement text to clarify the example.
> Within that text was the following delegate code, showing excellent use
> of the comma operator in a do-while loop-control context:
>
> (i) {
>      bool __done = false;
>      do {
>          writeln(i);
>      } while (__done = true, !__done);
>      // __done is still false if and only if the loop body executed
>      // a break and skipped the reassignment within the while test.
>      return __done ? 0 : 1;
> }

That loop body does not contain any breaks. It would be nice if the 
presented use case actually made sense. Also, just write

while(_done=true,false);

> That's actually rather tricky code.  In the general case for such a loop,
> you cannot simply move the "__done = true" assignment and place it at the
> end of the loop body,

Which a careless maintainer of the code might still do, and now you have 
a bug. Whatever your actual use case was, I think it is likely that 
there is a more elegant solution that does not require a comment (about 
control flow!) to prevent such accidents from happening.


More information about the Digitalmars-d mailing list