Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 5432 - Allow variable declaration inside while condition #342

Closed
wants to merge 1 commit into from

Conversation

yebblies
Copy link
Member

Implement two re-writes:
while(auto var = exp) body => for(typeof(exp) var; var = exp ;) body
while(type var = exp) body => for(type var; var = exp;) body

http://d.puremagic.com/issues/show_bug.cgi?id=5432

Implement two re-writes:
`while(auto var = exp) body` => `for(typeof(exp) var; var = exp ;) body`
`while(type var = exp) body` => `for(type var; var = exp;) body`
@WalterBright
Copy link
Member

I do not believe these rewrites are correct. The for statement has a separate initialization and assignment. Initialization and assignment are very distinct operations, and the rewrites confuse the two. I'm not sure there even is a correct answer here. Is the variable created once, default initialized, and then assigned to each time, or is a new one created and initialized each time through the loop?

For the programmer who wants to declare a variable, a for loop does the job in a straightforward manner.

@tgehr
Copy link
Contributor

tgehr commented Aug 28, 2011

The right answer is that the variable is created and initialized each loop iteration, because the loop condition is part of the loop.
Basically, the rewrites have a similar effect as the correct rewrite
while(auto var = condition) body =>

for(;;) {
    if(auto var = condition) body
    else break;
}

Which does not confuse anything. If you use a for loop for the same effect, you won't get type inference, which is not nice.

@ghost
Copy link

ghost commented Dec 21, 2011

I fully agree with tgehr. The "while" loop simply doesn't have any concept of initialization. Period.

Rather, the argument to while is a condition which is, by design, checked every time. Thus if we insert a declaration into this condition, the variable is redeclared/reassigned every single time.

This is especially useful in code like:

while(T elem = queue.pop()) {
    // use elem
}

which is definitely not an obscure example. This is also allowed in C++ thus should not come as a surprise to most experienced C++ programmers, which is your biggest demographic as far as I understand your PR messages.

braddr pushed a commit to braddr/dmd that referenced this pull request Oct 22, 2012
Strict @Property syntax compliance (-property)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants