NWNWiki
Advertisement
NWNWiki
3,718
pages

An increment or decrement operator is a programming construct that changes the value of a variable within an expression. (In a sense, they combine a simplified arithmetic operator with an assignment operator.) In NWScript, there is one increment operator, ++, and one decrement operator, −−, both of which share the same principles of use.

The NWScript increment and decrement operators are unary operators, meaning they operate on a single value. This value must be an integer variable, which will be increased (or decreased, in the case of the decrement operator) by 1 when the expression is evaluated. This can often simplify code whose primary purpose is to count something, as the counting can often be incorporated into another statement. Some care must be exercised, though, to make sure the variable containing the count is not changed too soon or too late.

The operator can occur before or after the variable it works on, and this choice affects the value of the expression as a whole. If the operator is before the variable (prefix notation), the increment (or decrement) occurs before the value is passed on the surrounding expression. Thus, the snippet

int x = 10;
int y = ++x;

causes the value of x to be increased to 11, then the value 11 is assigned to y. On the other hand, if the operator is after the variable (postfix notation), the increment (or decrement) occurs after the value is passed on the surrounding expression. Thus, the snippet

int x = 10;
int y = x++;

causes the value 10 to be assigned to y, then the value of x is increased to 11.

Since these operators are partially assignment operators, they can legitimately be used as stand-alone statements. That is, a statement like

nCount++;

is sometimes used when the value of nCount needs to be increased by 1, but the value is not needed at the time of the increase.

Advertisement