samedi 29 février 2020

When to use else if instead of if?

Suppose we have this code:

if (condition_1)
   do this
if (condition_2)
   do that
else
   do blablabla

And now this one:

if (condition_1)
   do this
else if (condition_2)
   do that
else
   do blablabla

And now let's check what happens line by line. If i'm not mistaken, the first program starts checking if condition_1 is true or false, then the same thing happens for condition_2. And if none of these conditions are true, the program runs "do blablabla".

The second program starts from checking condition_1, and if it's false then if checks condition_2. If condition_2 if false, if does nothing (by nothing i mean it ignores the else statement). If so, the second if statment from the second program can be replaced by:

if (!(condition_1) and condition_2)
   do that

But else then can be run, i thought that every else if statement can be replaced by only if with a bit longer condition. So is this possible to replace every else if by using only if? And when "do blablabla" will run?

Aucun commentaire:

Enregistrer un commentaire