What is the best way to make an if-lse?

Asked

Viewed 77 times

0

The two examples below are equivalent, but what represents the best way to make a if-else? My goal is to display "num é igual a 0" if num is equal to 0, and "num é diferente de 0" case num has any other numerical value.

Code 1

if (num == 0)
  puts("num eh igual a 0");
else
  puts("num eh diferente de 0");

Code 2

if (num != 0)
  puts("num eh diferente de 0");
else
  puts("num eh igual a 0");

Every time I write one if-else I brake and I have this doubt, whether I should first treat the specific condition in If and leave the rest to the Else as in Code 1, or the other way round, dealing first with most cases in If and leaving the specific case at Else as in Code 2.

Another question: suppose I have one if-else in which the blocks if and else have a different amount of lines of code, in which case the order matters? I mean, it makes a difference in the elegance and readability of the code the option that has the most lines of code be written first (within if) or last (within Else)?

  • 1

    Code 1 is generally preferable, but it all depends... the idea is to make the code as quickly understandable as possible and, most of the time, a denial can confuse a little more, but in a data validation section it may make more sense to Code 2. Anyway, it depends on... On the second question, particularly, I have never seen someone with this neura and I think it does not make so much difference, given that if an if/I get too big you can separate it into smaller methods. As a tip, take a look at the book "Clean Code".

  • 1

    Perhaps, depending on the case, there might be some difference in performance because of the branch Prediction, but then you will only know after you test. But at first, "whatever", depends a lot on each case.

1 answer

1

Well in the case you described

If(num){
   puts("num eh diferente de 0");
}else{
   puts("num eh igual a 0");
}

The code is read from above down so you should put the instruction lighter and discard as many options in the first if, but try to use the switch as much as possible since this has slightly more complex properties than reading from top to bottom. As for the compiler the speed with which it does == or != It’s the same since first there are several instructions in x64 or amd64 that make both comparisons but second because there is a significant difference between the two the compiler C itself (unless you’re using something obscure) makes the optimization of these little instructions by you So it has a lot to do with the readability of the code personally I prefer to do:

if(algoeum){
  printf("a variavel não é 0");
}

Since most people read the condition faster than other ways, but this depends on who’s reading your code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.