Shop OBEX P1 Docs P2 Docs Learn Events
Arrays can replace most "if" statements — Parallax Forums

Arrays can replace most "if" statements

trytryagaintrytryagain Posts: 26
edited 2009-09-27 14:50 in General Discussion
The forum has helped me out alot
specifically with the help of Peter Verkaik,
he is a great guy. Thank you Peter.

I thought I would give something back with
a little trick replacing most of your
"if" statements with an array.

Example:

if (shoesize == 1)
{ans = "This is a small foot"}
else
if (shoesize == 9)
{ans = "This is an average size foot"}
else
if (shoesize == 16)
{ans = "This is Bigfoot!"}

MyAnswer = ans;

Replace with:

static String shoeSizes [noparse]/noparse =
{"","This is a small foot",.......,"This is an average size foot", ETC};

Then your code looks like this:

cool.gif·myAnswer = shoeSizes[noparse][[/noparse]shoesize];

It processes faster, takes up fewer lines of code, and makes your code neater.

As you can see, it works great when you have lookups with small
index numbers fairly close to each other. You need to fill every index
range for it to work properly.

Happy Coding!

Jeff (trytryagain)












·

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2009-09-27 14:50
    Unused entries in the stringarray should be set to null, """, or "invalid shoesize"
    Strings do have quite a overhead due to the way stringtables are coded.

    Another alternative is to use switch

    switch(shoesize) {
      case 1: ans = "This is a small foot";
              break;
      case 9: ans = "This is an average size foot";
              break;
      case 16: ans = "This is Bigfoot!";
               break;
      default: ans = "invalid shoesize";
    } 
     
    
    

    regards peter
Sign In or Register to comment.