And / Or Operators [Solved]

Started by BrightBulb, Fri 31/08/2012 17:28:43

Previous topic - Next topic

BrightBulb

Hey everyone,

is there a way to replace for example if (A==1 && (B!=1 || B!=2 || B!=3) with something shorter?

I tried if (A==1 && B!= (1 || 2 || 3) but unfortunately it does not work.

The reason I ask ist that in my script it's of course not just A and B but something much longer so that it would make it much easier to read if I don't have to repeat the variables (B).

Khris

No, you can't group conditions like that. Depending on the actual values you're testing against and the possible values of A and B, there might be shorter ways though.
(B!=1 || B!=2 || B!=3) is a bad condition because it'll never be false. In case you meant (B!=1 && B!=2 && B!=3), that's equivalent to (B < 1 && B > 3).

If B is that much longer, use a substitute:
int b = really_long_expression;
if (b ...)

You can also assign the value of a condition to a bool variable. The following is valid code:
Code: ags
  bool cond = (A == 3 && B < 1 && B > 3);
  if (cond && C == 4) ...


There might be even better ways to shorten things, but we'd have to see your actual code.

BrightBulb

Yes I meant && of course.

The solution with the bool seems interesting.

Thanks.

cat

Quote from: Khris on Fri 31/08/2012 18:13:12
Code: ags
  bool cond = (A == 3 && B < 1 && B > 3);
  if (cond && C == 4) ...

B < 1 && B > 3 will never be true.
Use (B < 1 || B > 3) instead.

Khris


SMF spam blocked by CleanTalk