Struct Primer

From NWN Lexicon
Jump to navigationJump to search

A struct is a variable that can hold multiple values. Individual values are set or retrieved using the dot (".") operator.

The convenience of using a struct is that it can be easily copied using assignment operators, and makes for cleaner code than multiple enumerated (or unrelated) variables.

These are C-style structs, so you can't have member functions.

// the struct declaration
struct MyStruct
{
    // list of variables in the struct
    int a;
    float b;
};

// function declaration using a struct
void MyFunction(struct MyStruct strStruct);

void main()
{
    // Declare a couple of local variables based on the struct
    struct MyStruct strStruct1, strStruct2;

    // Access the components of the struct with '.'
    strStruct1.a = 5;
    strStruct1.b = 3.4;
    strStruct2.a = 7 - strStruct1.a;
    strStruct2.b = 8.5 - strStruct2.b;

    // Or use the struct as a whole
    strStruct1 = strStruct2;
    MyFunction(strStruct1);
}

// function implementation using a struct
void MyFunction(struct MyStruct strStruct)
{
    int x = strStruct.a;
    return;
}

 author: Ryan Hunt, editor: Charles Feduke, additional contributor(s): Jonathan Epp