KidTempo
KidTempo

Reputation: 930

Is it possible to to declare variables within a condition?

This is how I would do a while loop:

boolean more = true;
while (more)
{
  // do something
  if (someTest()) 
  {
    more = false;
  }
}

That's pretty standard. I'm curious to know if there's a way of doing something similar to the code below in Java: (I think I've seen something like it in C)

// The code below doesn't compile (obviously)
while (boolean more = true)
{
  // do something
  if (someTest())
  {
    more = false;
  }
}

I only ask this because currently I don't like the way I'm defining the variable used in the condition (in this case: "more") outside the scope of the loop, even though it's only relevant inside the loop. There's no point it being left hanging around after the loop has finished.


* * Update * *

An idea came to me following a visit to the Porcaline Chamber of Secrets:

for (boolean more=true; more; more=someTest())
{
  // do something
}

It's not perfect; It's abusing the for loop and I can't think of a way to execute the loop at least once, but it's close... Is there a way to make sure the loop is performed 1+ times?

Upvotes: 6

Views: 8392

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533670

To answer your question literally, you can do

for(boolean more = true; more; ) {
   more = !someTest();
}

but this is much the same as

while(!someTest());

If it must execute at least once you can do

do {

} while(!someTest());

Upvotes: 9

Sean Cogan
Sean Cogan

Reputation: 2586

KidTempo, in the example you gave, I think that more would be re-initialized each time through the loop. Each time through the loop, the conditional is re-evaluated, so assuming that you are able to define a variable in a conditional, the variable would be re-initialized each time that conditional is re-evaluated. This would also apply to other types of conditionals, so I would say to avoid defining variables in a conditional.

Upvotes: 0

Andrew Aylett
Andrew Aylett

Reputation: 40730

For your specific case, you can reduce your code to this:

while (true) {
  if (someTest()) {
    break;
  }
}

In general, you could replace your outer-scope declaration with an inner-scope one, but you'd need to move the loop condition:

while (true) {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
}

Or even:

do {
  boolean more=true;
  ...
  if (someTest()) {
    more = false;
  }
  ...
  if (!more) {
    break;
  }
} while (true);

I'd opine that defining your condition outside the loop is clearer.

Upvotes: 1

Related Questions