Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you usually set the default value before or set it in the else?

Tags:

optimization

Which one of the following do you do:

var = true;
if (...) var = false;

Or

if (...) var = false;
else var = true;

Is there a reason you pick on or the other?

I'm working on the premise that nothing else is happening to var. The next line of code might be something like:

if (var) { ... }
like image 515
Darryl Hein Avatar asked Jan 04 '09 17:01

Darryl Hein


2 Answers

How about var = { ... } directly since it's a boolean?

like image 90
krosenvold Avatar answered Sep 23 '22 14:09

krosenvold


I prefer the second in Java, doing something like this:

int x;
if (cond) {
  x = 1;
} else {
  x = 5;
}

because if something is changed later (for example, I turn the else block into an else if), the compiler will tell me that the variable has failed to be initialized, which I might miss if I used your first strategy.

like image 20
Ross Avatar answered Sep 21 '22 14:09

Ross