Is it bad to leave things on another if?

Say that you have only a limited number of possible conditions to call them a, b, c, d, and you are sure that any other possibilities are impossible.

Is it better to do

if(a)
  do_something();
else if(b)
  do_something();
else if(c)
  do_something();
else if(d)
  do_something();

or

if(a)
  do_something();
if(b)
  do_something();
if(c)
  do_something();
else
  do_something();
+3
source share
7 answers

If I understand correctly. else if they are checked only conditionally. The second would check each if there was no callback after each if.

+2
source

The standard method for this is to use the "switch" or "case" operator (depending on the language). For example, in PHP you should write:

switch ($condition) {
  case 'a': do_something(); break;
  case 'b': do_something(); break;
  default: do_something();
}

, . "default", - , - , "a" "b" ( !)

+1

, - else.

if(a)
  do_something();
else if(b)
  do_something();
else if(c)
  do_something();
else if(d)
  do_something();
else
  assert(0); // or throw ImpossibleException or whatever

( switch default)

, , - " " : - , ( enum) ; , .

+1

"" , , .

if(a)
  do_something();
else if(b)
  do_something();
else if(c)
  do_something();
else if(d)
  do_something();

, , if , , true, , .

if(a)
  do_something();
if(b)
  do_something();
if(c)
  do_something();
else
  do_something();

( , ), , if , true, . ( , c , else.)

, , , . switch, , , (.. break - goto ..), .

+1

, , true . , .

, return/break :

if(a)
  return do_something();
if(b)
  return do_something();
if(c)
  return do_something();
return do_something();

... return.

0

.

, else if , . , a , .

, .

, switch , . .

, : " ", . , !

0

The second version will evaluate each if statement regardless of the results of previous evaluations.

In fact, this will even show the wrong behavior for what you want to achieve, because the last else is always entered if the condition is not c. And not if he is not one of a, b or c.

The first version should work as expected.

0
source

Source: https://habr.com/ru/post/1796495/


All Articles