Killing the comma operator

Gopan via Digitalmars-d digitalmars-d at puremagic.com
Wed May 11 11:32:26 PDT 2016


On Wednesday, 11 May 2016 at 17:00:41 UTC, H. S. Teoh wrote:
> 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.

The problem with the second way is that the piece of code (scanf) 
that prepares the condition (x!=0) appears two times.  One before 
the while-loop and one towards the end of the while-loop block.  
In a maintenance project, this duplication is a problem.  
Somebody doing a bug fix is probable to do the fix in only one 
place, missing the other.  That was what I tried to avoid by 
using comma.  When there are multiple setup stattement, I too 
prefer the other trick (Nick Treleaven's comment)

do
{
    [ code that sets up condition-expression]

    if(expression)
        break;
}while(true);

> 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




More information about the Digitalmars-d mailing list