Page 1 of 1

Instead of using if, what else can i do?

PostPosted: Tue Jun 28, 2011 2:46 am
by Hblade
Is there any "other" method of using If statements? I know theres switch(int), but is there anything else?

Re: Instead of using if, what else can i do?

PostPosted: Tue Jun 28, 2011 12:03 pm
by Game A Gogo
something like...
Code: Select all
animpos=i<10?10-i:-i+10;


Condition?True:False

If Condition is true, return the True value, otherwise return the False value.

so here if i is smaller than 10, animpos will equal 10-i, otherwise it's equal to -i+10.

Although this is quite handy, there are inconvenient limitations. Like you can't use bit wise operators inside it like >> or << or %, and you can't use arrays in arrays

Re: Instead of using if, what else can i do?

PostPosted: Tue Jun 28, 2011 2:09 pm
by Hblade
True :/

Re: Instead of using if, what else can i do?

PostPosted: Tue Jun 28, 2011 2:29 pm
by DST
If isn't so bad, really. Computers were designed to do it lots of times every second.

But the real way to avoid if is to manage the resource flow. The more things fall into place on their own, or are queried in a sensible chain, the fewer if's you need.

One example would be on an rts game, instead of asking each unit 'what are you doing?', it would make the most sense to first ask it 'are you doing nothing?' Because when the answer is no, you don't have to ask any more questions to that unit for a while, and that's probably the most common answer....

And when using case switches, you can automate the process of determining the state of the switch. When events happen, the state gets switched. The more things you control with the switch, the fewer if's. For instance you may have a 5 case switch with if's inside of it, but couldn't you add some of those if's to the switch and have 8 cases? Sometimes switching a state even when the variable controlling the state doesn't need switched won't harm the switch and answers more questions about that actor.

Lastly, using equations to determine something can help.
if(x>0){
xvelocity=-1;}
else{
xvelocity=1;}

or

xvelocity=(-x/x);

produce the same result. (of course the second one won't account for 0's....there are always other things to work around. If it's a createactor script, simply don't spawn them at 0...).

But ifs will always remain a fundamental part of programming. Just keep them manageable.

Re: Instead of using if, what else can i do?

PostPosted: Tue Jun 28, 2011 2:59 pm
by Hblade
Thanks DST for useful info :)