"using the result of a comma expression is not allowed"
Steven Schveighoffer
schveiguy at gmail.com
Sun Apr 21 18:31:55 UTC 2024
On Sunday, 21 April 2024 at 16:28:47 UTC, Don Allen wrote:
> I just ran across "using the result of a comma expression is
> not allowed" in a situation where I used a comma expression as
> I would in C, expecting its value to be the value of the
> right-most expression.
>
> While D's language document is accurate in explaining how the
> comma expression is treated in D in 11.5, that treatment
> conflicts with 11.1:
> "Expressions are used to compute values with a resulting type.
> These values can then be assigned, tested, or ignored.
> Expressions can also have side effects."
>
> This restriction makes no sense to me, nor does calling this an
> "expression" if you can't use its value.
Comma expressions can make code with typos be accepted causing
confusing problems.
The compromise, since comma expressions are useful in the update
section of `for` loops, was to simply disallow using the value of
the expression.
In my experience with C, by far the most common use of comma
expressions is to expand macros in expression context. Obviously,
we don't need that in D, you can do the same thing with a lambda
in D.
A very notorious misuse of comma expressions was in Andrei's "The
D Programming Language" book, where it was stated that
`synchronized(A, B)` would protect the following block by locking
`A` and `B` in the proper sequence. However, this feature was not
implemented, instead, `A, B` was a comma expression, and only `B`
was locked.
As also noted by others, we may reuse the comma expression syntax
for tuples somehow, which only works if you can't use comma
expressions to mean "only the last thing".
-Steve
More information about the Digitalmars-d
mailing list