On Sunday, 10 October 2021 at 12:01:33 UTC, rempas wrote:
> This is the first time I'm finding something like that. I'm having the following code in C:
if (0 == (i >> 7)) {
if (len < 1) return -1;
v = i;
return *ret = v, 1;
}
This is part of a function that returns an int
. When I'm running this in C, it works. However in D, I'm getting the following error message:
Error: Using the result of a comma expression is not allowed
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)?
Hello rempas.
The comma-operator ,
is like ;
but results in an expression value, not a statement like ;
would. The left side of ,
is executed like a statement and the value of the right side of ,
is returned. Comma-expressions are merely used to pack additional instructions into places where only expressions are allowed.
if (x = y, myNiceFunction(), yay(x), x > 5)
{
// ...
}
or
if (hasFancyFunkyStuff)
x = z, fancy(x), funkyUpdate(z); // too lazy for braces
Many consider the ,
operator to be a design-flaw because it makes expressions difficult to read and can be easily abused because the above should actually be:
x = y;
myNiceFunction();
yay(x);
if (x > 5)
{
// ...
}
In D
you can still write the second example of code but not the first example of code. The designers of D thought they could make it less painful by just forbidding comma-expressions to be used as expression value and only as statement. This is because then comma-expressions can still be used in for
-loops:
for (x = y, z = a; x < z; x++, z--)
{
;
}
In conclusion, your C snippet should actually look like:
if (0 == (i >> 7))
{
if (len < 1)
return -1;
*ret = v = i;
return 1;
}
The previous snippet even could mislead readers to think that it would return a tuple of two elements which it doesn't.