Function Prototypes

From NWN Lexicon
Jump to navigationJump to search

Functions can be prototyped and declared, or just prototyped. A declared function has its function body immediately following the prototype of the function, where as a prototyped function declares the function name and applicable parameters, but does not define it until later in the file.

Because the compiler compiles source code in a top-down fashion, function prototyping is useful to organize code. It is common programming practice to put your int StartingConditional() as the first defined function in the file so it is easy to find. Placing function prototypes above a function that calls them allows the compiler to "know" about the functions that appear later on in the file so it can properly compile.

// prototype of a function
int GetSomeNumber(string sName);
// note: no function body!

void main()
{
    // statements ...
    int nBlah = GetSomeNumber("Chuck");
    // this compiles because the compiler "knows" about the GetSomeNumber
    // thanks to our prototype that appears above
}

// now we actually define the function that was prototyped above
int GetSomeNumber(string sName)
{
    if (sName == "Chuck")
        return 25;
    else
        return 0;
}

Unlike traditional C, you can't prototype a function with just variable types; you must include a variable name as well (the variable name in the prototype and variable name in the function do not have to match, but it is recommended that they do). For example:

// this will NOT compile
void PrintValue(int);

void main()
{
    PrintValue(6);
}

void PrintValue(int nValue)
{
    PrintInt(nValue);
}

The above does not compile because the prototype must include a variable name. The following, however, will compile:

// this WILL compile
void PrintValue(int nValue);

void main()
{
    PrintValue(6);
}

void PrintValue(int nValue)
{
    PrintInt(nValue);
}

BioWare uses function prototypes in nwscript.nss which in turn shells out to an external library that provides all of the function definitions for several functions.


 author: Charles Feduke