Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to to declare variables within a condition?

Tags:

java

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?

like image 926
KidTempo Avatar asked Aug 02 '12 17:08

KidTempo


People also ask

Can we declare variable in if condition?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Can you declare a variable inside a function?

A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters.

Can you declare a variable in an if statement JavaScript?

Should you define a variable inside IF statement? Honestly, there's no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.

Can you declare a variable in an if statement Python?

python allows creation of variables in an if... elif... else... clause, so that they can be used also outside the conditional block. This is also true for nested conditionals.


1 Answers

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());
like image 57
Peter Lawrey Avatar answered Nov 09 '22 05:11

Peter Lawrey