comma operator

Derek Parnell derek at psych.ward
Mon Mar 10 14:58:26 PDT 2008


On Mon, 10 Mar 2008 12:36:52 -0400, Sivo Schilling wrote:

> 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
> 

Excuse me for butting in and please don't take this the wrong way, but
would one write obscure or idiomatic code like this example, instead of
making the code plainly FO to any future maintainer?

I admit that I'm not actually sure what your code is trying to achieve, but
I've tried to make a more obvious implementation below. So, why are the
functions below a poorer implementation of your code? 

int validate(int pos)
{
    if (pos <= 2)
        return 0;
    else 
        return pos - 2;
}

And if you *must* have only a single line return ...

int validate(int pos)
{
   return (pos <= 2 ? 0 : pos - 2);        
}



-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell


More information about the Digitalmars-d-learn mailing list