Correct way of writing long or statements

Hey just been wondering this for a while , when I have an if statements with a ton of || in it. This is a super super simple example but obviously there will be more variables etc.

if (variable 1 != variable 3 && variable 4 != variable 5 || .....)

The list sometimes will go on for a longggg way I am just wondering weather in coding practice thats fine or if there is a "proper" way to break up the code to make it more readable/easier to work with?
Last edited on
Wrap the logic inside a boolean function, assuming you won't have a similar problem by having to pass in a ton of arguments.
Wherever you actually do the 'if' statement, remember that whitespace is your friend!
1
2
3
4
if ( (var1 != var2)     ||
     (!isItAFullMoon()) ||
     (var3 == var4)     ||
     (etc...) )

If it really goes on for a long time, there may be an alternate control flow structure you can use, or you may want to consider a lookup table.
Last edited on
I've found that the need for these kinds of if statements are rare and if you find yourself having to write one, it's a bigger sign of a design problem.

That said... in the few times I actually DO have to do something like this I tend to split up things on multiple lines:

1
2
3
4
if( something == somethingelse ||
    something2 == foobarbaz      )
{
}


EDIT: ninja'd!
Last edited on
Topic archived. No new replies allowed.