samedi 25 février 2017

How to properly use if/else/return-statements?

Suppose the following function:

int foo(int a){
  if(a == 1)
    return a;
  if(a%2 == 0)
    return a/2;
  else
    return a+1;
}

What are the dis-/advantages of leaving the else-keyword away?

In general is there any dis-/advantage of leaving the else-keyword away if we checked for certain conditions, that would have caused the function to terminate. Such that the code remaining code will only be executed if all of them have been false.

->I guess a if/else-if/else block would have been best in this situation, but it's meant to serve as an example.

Aucun commentaire:

Enregistrer un commentaire