Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference in for loop condition?

I have a simple question that I am posing mostly for my curiousity.

What are the differences between these two lines of code? (in C++)

for(int i = 0; i < N, N > 0; i++)

for(int i = 0; i < N && N > 0; i++)

The selection of the conditions is completely arbitrary, I'm just interested in the differences between , and &&.

I'm not a beginner to coding by any means, but I've never bothered with the comma operator.

Are there performance/behavior differences or is it purely aesthetic?

One last note, I know there are bigger performance fish to fry than a conditional operator, but I'm just curious. Indulge me.

Edit Thanks for your answers.

It turns out the code that prompted this question had misused the comma operator in the way I've described. I wondered what the difference was and why it wasn't a && operator, but it was just written incorrectly. I didn't think anything was wrong with it because it worked just fine. Thanks for straightening me out.

like image 707
CodeFusionMobile Avatar asked Jul 07 '09 21:07

CodeFusionMobile


People also ask

Which is faster while or for loop?

The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.

Which is faster while or for loop Java?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

Is for loop faster than other loop?

so none of them is faster than the other. Whatever may be the form of loop, the test condition will take same time.

How can loop performance be improved?

The best ways to improve loop performance are to decrease the amount of work done per iteration and decrease the number of loop iterations. Generally speaking, switch is always faster than if-else , but isn't always the best solution.


1 Answers

Using a comma like that will simply discard the first condition.

The comma operator means "run these statements in this order, and take the value of the last one".

like image 173
RichieHindle Avatar answered Sep 22 '22 08:09

RichieHindle