Killing the comma operator
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Wed May 11 10:00:41 PDT 2016
On Wed, May 11, 2016 at 04:46:48PM +0000, Nick Treleaven via Digitalmars-d wrote:
> On Wednesday, 11 May 2016 at 13:29:56 UTC, Gopan wrote:
> >int x;
> >while( scanf("%d", &x), x!= 0) // until user input 0.
> >{
> > //do something with x
> >}
> >
> >Without the comma operator, I would have to repeat the scanf
> >statement.
> >int x;
> >scanf("%d", &x);
> >while(x != 0)
> >{
> > //do something with x
> > scanf("%d", &x);
> >}
>
> Aside from scanf specifics, you shouldn't repeat the setup code, use
> do...while(true) with if and break.
[...]
Actually, the 2nd way he wrote it above is my preferred way, because it
reveals the correspondence between the structure of the code and the
structure of the data better than any of the various shortcuts people
like to write.
But a far superior way is to encapsulate reading input as a range (or
equivalent data source) and completely separate the data source from the
data processing:
auto scanInts() {
struct Range {
bool empty = true;
int front;
void popFront() {
if (scanf("%d", &front) > 0)
empty = false;
}
}
Range r;
r.popFront();
return r;
}
foreach (x; ScanfRange().until!(x => x != 0)) {
// do something with x
}
This way your data processing code doesn't ever have to worry about the
dirty details of how to loop over scanf calls, and can easily be hooked
into a different data source with minimal changes.
T
--
I am Ohm of Borg. Resistance is voltage over current.
More information about the Digitalmars-d
mailing list