I am looking for an easy to way to combine these 2 if statements in my Cocos2D application. However my attempts so far have not worked at all.
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I believe your attempt to combine the if statements into one stems from your problem actually understanding the statement. As a programmer, your first and foremost duty is to write readable code even if you’re the only person ever to read it. The other reason I can think of why you want only one if statement is that somehow you think this will be faster.
So first I would start by moving all calculations out of the if clauses. Not only is this repetitive, it is also error prone and very hard to read. I’ve also taken the liberty to replace division by two with multiplication by 0.5f because the ARM processors do not have a division instructions, therefore the divisions are executed by software and rewritten as multiplication anyway. It’s possible the compiler already optimizes this but nevertheless good practice to avoid division operations if you can.
So here’s how I would write the statement. The additional local variables cause no performance penalty. Usually the compiler will do something like that anyway. Similarly, if spriteA.tag is not 1, the condition doesn’t evaluate the rest of the first if condition and jumps right to testing the else if part. This is called “early out”: on the first test which will cause the entire condition to fail the program will stop evaluating the remaining tests because there would be no point in doing so. Therefore it is good practice to begin an if statement (or nested ifs) with the condition that is most often going to fail.
Needless to say, you can’t combine this into a single if statement. At the end you perform two different functions (update position based on either spriteA’s or spriteB’s y position). Therefore you require to have two branches.
If you wanted to, you could add
died == NOas the first test in both nested if statements if you really want to avoid the outermost if clause. However doing so will have your program always test fordied == NOtwice even though the died variable will not change. On the other hand it’s possible that the compiler also recognizes and optimizes this situation.