Search code examples
optimizationloopssyntaxexecutioncontinue

Continue loop Inside if statement vs. using the negation of the if statment inside the loop


For example lets consider the following 2 codes:

for (i = 0; i < 1000; i++)
{
   if ( i % 2 != 0)
   {
       continue;
   }
   else
   {
     ...  
   }    
}

and

for (i = 0; i < 1000; i++)
{
   if (i % 2 == 0)
   {
     ...  
   }    
}

Both will lead to the same result. So which one to use? Which one is better? Are there any significant performance differences between the two? Lets see what you guys see about this. I like the discussions I see here about these things. This may lead to better code writing and better execution times. I posted this question because I did not find the answer to it. I may post another one like this in the future if I did not find an answer to it.

P.S. Whats the purpose of using continue inside a loop when you can go without it?


Solution

  • In this specific example? There's no purpose in using continue whatsoever.

    As you mentioned, both code samples produce exactly the same results. And neither will be detectably faster than the other.

    The decision you make of which one to prefer should be based on readability and clarity, rather than some type of misguided "optimization" attempt. With that in mind, the second is far clearer. I'd seriously question the programming chops of someone who used the first in a real codebase.

    As a basic guideline, never use an if-else when a single if will do. In this case, you're comparing != and then finding the opposite of that with an else statement—that's almost like saying !(!=), which produces a double-negative. Very hard to read or understand. In general, you should try to evaluate positive conditions in an if statement, rather than negative ones, to prevent precisely this.

    And there's really no reason to post additional questions that are similar to this one. All of the answers will be the same. Ignore any possible performance difference (if one even exists, which is quite unlikely, given an optimizing compiler), and focus on which version makes the most sense to you as a human being who has to read it. Please ignore anyone who gives you advice to the contrary.