views:

89

answers:

5
+3  Q: 

Swap if-statements

Hi,

I am working on code minimization and enhancement. My question is: is it possible to swap the if statements above without destroying the logic of the code?

    int c1 = Integer.parseInt(args[0]) ;
    int c2 = Integer.parseInt(args[1]) ;
    int c3 = Integer.parseInt(args[2]) ;

    if (c2-c1==0)
      if ( c1 != c3 )

Since between the both if statments are no operations that write the variables I would say yes but I am not sure.

Any ideas?

+1  A: 

Yes. You can also write if ((c2-c1==0) && (c1 != c3)).

ob1
+1  A: 

If you mean

if ((c1 != c3) && (c2-c1==0))

and you do not plan to do something special only if c2-c1==0 then yes.

thelost
+1  A: 

If there are no else blocks involved, then I suggest you to write it as:

if (c2-c1==0 && c1 != c3 )

or, if you want to swap them,

if (c1 != c3 && c2-c1==0)
LucaB
+10  A: 

I don't really see why you want (c2 - c1 == 0) instead of c1 == c2

why not go the

if ((c1 == c2) && (c1 != c3)){
  do_stuff();
}

or

if ((c1 != c3) && (c1 == c2)){
  do_stuff();
}

route

As a note, there is no penalty or advantage in switching c1 for c2 anywhere. Of the above, putting the most likely to fail condition first is slightly more efficient, because the second condition will not be evaluated if the first one fails.

Also note, this is a micro optimisation, you should never be considering for speed.

Third note, if your program doesn't do anything else, and exits if this condition doesn't hold, and you really do want to micro-optimise (which you don't) I suggest not parsing the arguments before you know they are needed. if c1 will be unequal to c2 most of the time, then you can wait with parsing c3 until you know you have to check against it. This is strictly theory. Don't do this in practice as it will make your code that much harder to read. It's much clearer to process all the commandline vars to something sensible as soon as you can.

Martijn
+3  A: 
int c1 = Integer.parseInt(args[0]) ;
int c2 = Integer.parseInt(args[1]) ;
int c3 = Integer.parseInt(args[2]) ;

if (c2 == c1 && c1 != c3 ) {
   ...
}
Adeel Ansari