if condition - best practice?

Hello, New to C++, I am learning on this site and thanks to the forum.
I am experimenting if statements while iterating through a vector:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int myNumber;

  for (int i=0; i<myVector.size(); i++) {
		
        
         if (i>0 && i%myNumber != 0) {

             //first event
         }
        
         if (i>myNumber){
             
             //second event

         }


I do not often see multiple if statements like that. I was wondering if it was a good practice to do so.
In my case I can't use switch or else if because some indexes will trigger both events.
would it be better practice to create a second for loop to perform the second if statement?

Thank you
There are cases when you cannot use a single if-elseif-else to cover all the cases. I know what you mean: it feels messy. However, it is perfectly normal. In some cases you may actually be able to rework the conditions so you only need one if-elseif-else chain, but that isn't always the case.

In your particular case, you should consider what you want to happen when both conditions are true. Should both be executed? Should only one be executed? Should neither be executed? It looks like you want to allow both to be executed, so your current code is fine.

Splitting into two loops is only necessary if you don't want the order of the executions to interleave.
Last edited on
I think what you do is fine. It's how I usually do it myself.
Thank you for your prompt replies LB, and Peter. Indeed, both need to be executed. (great to learn something with such an active community)
Last edited on
Topic archived. No new replies allowed.