Select to view content in your preferred language

In C, avoid using several nested if statements.

592
0
07-18-2022 01:40 AM
MubashshirHasan
New Contributor II

I'm considering avoiding nested if statements in my code.

 

 

for (i = 0; i < N; i++) {
  if(x & y != 0) {
     if(z & k ==  z) {
        if(w & ( (c || u) && f)) { 
            //  Do something with the checked condition
        }
      }
    }
 } 
  

 

 

The for loop, followed by many if statements, appears to be unattractive. Also, the variables x, y, z, k, and so on are of the type edgeBag. edge weight or even wider than that in width, making it look more worse.

One possibility is to utilize variables to store the x, y, z, and so on, and then use the variables within the if statement to check the condition.

 

 

 for (i = 0; i < N; i++) {
 a = x;
 b = y; 
 ...
   if(a & b != 0) {
       ...
          ...
           // .....
    }
  }

 

 

Before posting a question here I've checked various other websites like Scaler. This did not bother me at first, but as the pattern became more frequent, it became bothersome. Is it possible to avoid this pattern? Or, to put it another way, Thanks.

0 Kudos
0 Replies