What is a "comma expression"?

Adam D Ruppe destructionator at gmail.com
Sun Oct 10 12:19:39 UTC 2021


On Sunday, 10 October 2021 at 12:01:33 UTC, rempas wrote:
>     return *ret = v, 1;

The comma expression in C is a combination of two things but in 
the context of another thing. Well that's not very good, but like 
there's statements and expressions. Statements do something but 
do not have a value. So `if() {}` and `return` and `for() {}` are 
statements, because they don't have a value you can assign to a 
variable.

Expressions do something but DO have a value and thus you can 
assign it to a variable.

a = if (true) { a } ; // not permitted because if is a statement

a = 5 + 4; // OK, 5+4 is an expression and thus has a value


This is a slight simplification but generally true. You'll notice 
in some languages the if assign does work; in those languages you 
have an if expression rather than an if statement.

The language grammar has rules for where statements are allowed 
and where expressions are allowed and you can't mix and match 
(unless the grammar has two rules, one allowing each type).


Anyway, the C comma expression is a combination of two other 
expressions where the first one is evaluated, but its value 
discarded, then the second part becomes the value of the whole 
expression.

a = 1, 2; // the 1 is discarded, so a == 2


It is actually the same as writing out:

1; // evaluate this then discard it
a = 2; // eval this and actually keep the value


The difference being that it is allowed in an expression context.


So that `return *ret = v, 1;`

Could just be written

*ret = v; // this is eval'ed and value discarded
return 1; // second part value is kept


And idk why they didn't just do that here. But the C thing is 
most commonly seen in a for loop:

for(a = 0, b = 0; a < 5; a++, b++) {}


because the grammar only allows an expression in each piece of 
the for loop, so you can't separate the two steps by semicolons 
like you do in different contexts.

> Can someone explain what comma expressions are and why they 
> don't work in D (or if the only doesn't work as returned values 
> from a function)?

D considers it a bit obscure and special-case to use the comma 
for. There was talk a while ago about making the comma do 
something else instead, but this never materialized.

But you can always write it out longer form, perhaps wrapping it 
in a function.

// what I would do here:
*ret = v;
return 1;

// or if you absolutely had to have it in an expression context:

return (){ *ret = v; return 1; }();


The nested function there explicitly does what the comma operator 
does and is allowed in expression context as well.


More information about the Digitalmars-d-learn mailing list