Switch case Statement

From NWN Lexicon
Jump to navigationJump to search

switch/case Statement

The switch statement operates like a series of "if...else" statements on the same condition. It makes the code clearer and easier to maintain if one value is being tested multiple times. However, only integers can be used as the comparison in a case statement (integer constants can be used, as long as they are properly defined). As of version 1.87.8193.35 of NWN:EE, strings can also be used by hashing them with HashString(). See the HashString() page for an example.


The following examples have the same effect:

int x = 0;
// if block
if (x == 0)
{
     // statements ...
}
else if (x == 1)
{
     // statements ...
}
else if (x == 2)
{
     int y = 2;
     // statements ...
}
else if (x ==3 || x ==4 || x ==5 ) {
      // statements ...
}
else
{
     // statements ...
}

// switch block
// the above if/else block is functionally equivalent to the below
// switch statement. In fact, they are compiled to the same code.
switch (x)
{
case 0:
     // statements ...
     // without a break execution would continue.
     // In this example if we didn't use a break, the case 1: code would
     // also be executed if x == 0.
     break;  
case 1:
     // statements ...
     break;
case 2: {
           int y = 2;  // y is only visible inside these brackets.
           // other statements ...
           break;
        }
case 3:
case 4:
case 5:
     //statements ...
     break;

default:
     // statements ...
     break;
}

The variable x is passed into the switch statement and compared to the value after the case statement. If none of the case statements equal x then the optional default code block is executed.


It is important to include the break statement at the end of each case code block to escape from of the switch statement, or the following cases will execute also (however, sometimes this is a desired effect). The ability to fall through makes switch/case different from if..else. In the example above we could do something specific in case 3, exclude a break and then have the statements under cases 4 and 5 execute as well. That would require duplicating code or adding an additional comparison in the if..else method.


It should also be noted that you can declare and initialize a variable within a case statement but you must use brackets to make a new scope so the variable won't be visible outside that scope. See case 2: in the example.




 author: Ryan Hunt, editor: Grimlar, additional contributor(s): Rich Dersheimer, Simon Hassall, Seth Ellsworth