for in D versus C and C++

Denis Koroskin 2korden at gmail.com
Thu Mar 19 10:43:18 PDT 2009


On Thu, 19 Mar 2009 20:32:54 +0300, Walter Bright <newshound1 at digitalmars.com> wrote:

> BCS wrote:
>>> Thu, 19 Mar 2009 06:35:37 -0400, Steve Teale wrote:
>>>
>>>> for (; a<b; a++);
>>>>
>>>> is illegal in D.
>>>>
>>>> Doesn't this break a lot of C and C++ code?
>>>>
>>> for (; a<b; a++) {}
>>>
>>> is legal.  I don't think that an empty statement after for is used in
>>> "a lot of code."
>>>
>>  it's a trivial fix and easy to find. Heck, you hardly need to think!
>
> No, it isn't easy to find. This is in D because a colleague of mine, who  
> was an expert C programmer (the best in the company I was working for),  
> came to me with:
>
> for (xxx; i < 10; i++);
> {
>       ... code ...
> }
>
> and said he could not figure out why his loop executed only and exactly  
> once. He'd fiddled with it for a whole afternoon. He said he must be  
> missing something obvious. I said you've got an extra ; after the ). He  
> smacked his head and about fell over backwards.
>
> So it's illegal in D, along with:
>
>     if (condition);
>
> and similar constructs. Have to use a { } to indicate a blank statement.

Funny enough, or programming department chief posted the following question in our corporate newsgroup:

Why the hell this function enters infinite loop?

void treeWalkWithoutRecursion( Node* head )
{
    Stack   s;
    s.push( head );
    while ( !s.empty() );
    {
        Node* tmp = s.pop();
        if ( !tmp->marked )
        {
            if ( tmp->right  )
                s.push( tmp->right );
            s.push( tmp );
            if ( tmp->left )
                s.push( tmp->left );
            tmp->marked = true;
        }
        else
            doSomeThing( tmp );
    }
}



More information about the Digitalmars-d mailing list