if/else Statement

From NWN Lexicon
Jump to navigationJump to search

if/else statements are used to control the flow of code execution. This is best illustrated with an example:

int bAlpha = FALSE;
int bBravo = FALSE;

if (bAlpha) 
{
     // statement 1 ...
} 
else if (bBravo) 
{
     // statement 2 ...
}
else
{
     // statement 3 ...
     // in this example, this is the code that is executed because
     // both bAlpha and bBravo are FALSE
}

If bAlpha evaluates to TRUE then statement 1 will execute. If it evaluates to FALSE then it will skip to the next if else and evaluate bBravo. If neither bAlpha or bBravo evaluates to TRUE then statement 3 will execute as the default (catch-all).

if statements can also be used alone without if else or else statements:

int bCondition = TRUE;
if (bCondition) PrintString("TRUE!");

If bCondition evaluates to FALSE it will skip PrintString("TRUE!") and move on to the next line of code.

In NWNEE you can optimise away dead branches at compile time only when constants are evaluated to FALSE, eg:

// If set to 1 / TRUE or similar it will print the message, else will never print (it is compiled away).
const int DEBUG = 0;

void main()
{
    if (DEBUG)
    {
         SendMessageToPC(GetFirstPC(), "DEBUG code block");
    }
}

Version

This primer was updated in 1.89.8193.37 of NWN:EE. scriptcomp: Will optimize away dead branches when an if condition is a constant.



 author: Ryan Hunt, editor: Charles Feduke