cadmy
cadmy

Reputation: 535

Where should variables be declared?

I have a complicated condition inside else block inside a loop. So I decided to form some new variables to simplify this condition. Where should I declare these variables?

//here 1
for (...) {
   //here 2
   if(...) {

   } else {
      //here 3
      if (cond1 && cond2){}
   }
} 

Upvotes: 0

Views: 106

Answers (3)

Fabrizio Morello
Fabrizio Morello

Reputation: 335

Probably the best solution is this :

 boolean cond1,cond2 = false;
    for (...) {
       //here 2
       if(...) {

       } else {
          cond1 = ...
          cond2 = ...
          if (cond1 && cond2){}
       }
    } 

this allows you to allocate no memory for variables at each iteration.

Upvotes: 1

pkalinow
pkalinow

Reputation: 1741

You should declare variables where they are needed, so in this case probably in here 3.

Upvotes: 2

amit
amit

Reputation: 178521

You should declare variables closest as possible to their usages, and in the "smallest" scope possible.

In your example, if cond1,cond2 are used ONLY when you write them in the sample, they should be declared in here 3.

Upvotes: 4

Related Questions