comma operator

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon Mar 10 10:38:30 PDT 2008


"Sivo Schilling" <i-b-p at gmx.net> wrote in message 
news:fr3o34$sc7$1 at digitalmars.com...
> In C/C++ comma operator allows grouping two statements where one is 
> expected.
>
> Example (C/C++):
> -------
> #include <stdio.h>
>
> int validate(int pos)
> {
>    return (--pos <= 0 || --pos <= 0), pos;
> }
>
> void main()
> {
>  printf("validate(1) gives %d\n", validate(1));
>  printf("validate(2) gives %d\n", validate(2));
>  printf("validate(10) gives %d\n", validate(10));
> }
> -------
> Output:
> validate(1) gives 0
> validate(2) gives 0
> validate(10) gives 8
>
> The example above now in D (DMD 1.x/2.x):
> -------
> import std.stdio;
>
> int validate(int pos)
> {
>    return (--pos <= 0 || --pos <= 0), pos;
> }
>
> void main()
> {
>  writefln("validate(1) gives ", validate(1));
>  writefln("validate(2) gives ", validate(2));
>  writefln("validate(10) gives ", validate(10));
> }
> -------
> Output:
> validate(1) gives 1
> validate(2) gives 2
> validate(10) gives 10
>
> Is this expected behaviour or if there's something I've missed ?
> Any suggestions ?
>
> Regards, Sivo.

It seems like a compiler bug.  See, the first part of the comma expression 
has to be evaluatable as a statement, but you'll notice that if you write:

--pos <= 0 || --pos <= 0;

The compiler will give an error since the second part of the || is not a 
statement.  If you change it to:

--pos <= 0 || --pos;

It works, since --pos can exist on its own.  Similarly, if you change your 
function to:

return (--pos <= 0 || --pos), pos;

It works just like the C/C++ version.

The compiler should detect that the first part of the comma expression is 
not a valid statement and should issue an error to that effect, as it does 
when it's used on its own.

What's weird is that if you look at the disassembly of the buggy version of 
the function, the compiler never even outputs code for the first part of the 
comma expression.  It's almost exactly as if you wrote:

int validate(int pos)
{
    return pos;
} 




More information about the Digitalmars-d-learn mailing list