comma operator
Sivo Schilling
sivo.schilling at web.de
Mon Mar 10 15:52:45 PDT 2008
Hi Derek,
the code snippet you've seen is a simplified excerpt of a more complex
type of return statements in an existing C++ toolkit, which i try to convert to the D programming language.
I agree that the way you are suggested could be gone, but nevertheless its's a litte bit annoying that well known solutions from very old C-times
(and i lived with C during the past twenty vears) could not be D'ed as
expected.
Derek Parnell Wrote:
> 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