Constants and const keyword

From NWN Lexicon
Jump to navigationJump to search

A constant is a symbol (or label) to represent a value that should not change during program execution (traditionally constants are symbols that are replaced by the precompiler with their actual values - or constant definition - before compiling).

Constants are a great way to make code more readable and much easier to maintain. Also it is useful when a value may change at some point; one can simply change the constant's definition once without having to change the value throughout all the source code and recompile.

With patch 1.30, NWScript took a nice step forward by including a const keyword. Prior to that, the only way to make your own true constants (i.e., constants whose value can never change, unlike variables) was to edit the file nwscript.nss, which was something you really shouldn't do. With the const keyword, that is no longer necessary. There are three data types that you can use for constants, and the syntax is as shown:

const int    MY_INT    = 3;
const float  MY_FLOAT  = 3.00;
const string MY_STRING = "Three";

By convention, variables should be all lowercase and constants all uppercase, though you're of course by no means obligated to do so.

A good idea with constants is to put them in an include file - if you include a file with constant definitions, all files including it will use those constants.

The last thing to note is: Why should I even care about using constants?

One thing that's important to note is that variables can't be used as cases in switch statements. So you couldn't do this:

void main()
{
    int nSomething;

    int nValue1 = 10;
    int nValue2 = 20;

    switch (nSomething)
    {
        case nValue1:
            SpeakString("10");
            break;
    case nValue2:
            SpeakString("20");
            break;
    }
}

But you can do this:

const int nValue1 = 10;
const int nValue2 = 20;

void main()
{
    int nSomething;

    switch (nSomething)
    {
        case nValue1:
            SpeakString("10");
            break;
        case nValue2:
            SpeakString("20");
            break;
    }
}

Another use for the const keyword is that you cannot use variables as default values in your functions. So this won't work:

int nVar = 3;

void SomeFunction(int nInput = nVar)
{

}

But you can do this:

const int nVar = 3;

void SomeFunction(int nInput = nVar)
{

}

 author: Charles Feduke, editor: Lilac Soul, additional contributor(s): Iskander Merriman, David Delmont, C-fu