Reputation: 3153
Why can I do this:
if (int result=getValue(); result > 100) {
}
but cannot do this:
while (int result=getValue(); result > 100) {
}
Why discriminate against while
? A condition is a condition. Why while
cannot evaluate it like if
can?
In order to achieve the desired behavior with while
, I'd have to implement it this this way:
int result = getValue();
while (result > 100) {
//do something
result = getValue();
}
Upvotes: 3
Views: 7298
Reputation: 60258
There are 3 reasons I can think of for not adding this syntax.
There is a perfectly suitable construct, namely the for
loop, that can be used for exactly this purpose.
Adding any feature to the language is a lot of work, and a very strong case needs to be made for such a proposal. Given the first point, I don't see this happening.
In my opinion this is the most important one: If this feature were added to the language (let's say for a convenient syntax, or something like that), then it can essentially never be removed from the language. This means that the while (;)
syntax is forever banned, and there could very well be some other semantics that we would like to express using such a syntax, and giving up this option is not something that should be done without careful thought.
Upvotes: 5
Reputation: 303457
Because we already have a while-loop-with-initializer. It's spelled:
for (int result=getValue(); result > 100;) {
}
Upvotes: 18