5.5 Expressions

Expressions in NASM are similar in syntax to those in C.

NASM does not guarantee the size of the integers used to evaluate expressions at compile time: since NASM can compile and run on 64-bit systems quite happily, don't assume that expressions are evaluated in 32-bit registers and so try to make deliberate use of integer overflow. It might not always work. The only thing NASM will guarantee is what's guaranteed by ANSI C: you always have at least 32 bits to work in.

NASM supports two special tokens in expressions, allowing calculations to involve the current assembly position: the $ and $$ tokens. $ evaluates to the assembly position at the beginning of the line containing the expression; so you can code an infinite loop using JMP $. $$ evaluates to the beginning of the current section; so you can tell how far into the section you are by using ($-$$).

The arithmetic operators provided by NASM are listed here, in increasing order of precedence.

5.5.1 |: Bitwise OR Operator

The | operator gives a bitwise OR, exactly as performed by the OR machine instruction. Bitwise OR is the lowest-priority arithmetic operator supported by NASM.

5.5.2 ^: Bitwise XOR Operator

^ provides the bitwise XOR operation.

5.5.3 &: Bitwise AND Operator

& provides the bitwise AND operation.

5.5.4 << and >>: Bit Shift Operators

<< gives a bit-shift to the left, just as it does in C. So 5<<3 evaluates to 5 times 8, or 40. >> gives a bit-shift to the right; in NASM, such a shift is always unsigned, so that the bits shifted in from the left-hand end are filled with zero rather than a sign-extension of the previous highest bit.

5.5.5 + and -: Addition and Subtraction Operators

The + and - operators do perfectly ordinary addition and subtraction.

5.5.6 *, /, //, % and %%: Multiplication and Division

* is the multiplication operator. / and // are both division operators: / is unsigned division and // is signed division. Similarly, % and %% provide unsigned and signed modulo operators respectively.

NASM, like ANSI C, provides no guarantees about the sensible operation of the signed modulo operator.

Since the % character is used extensively by the macro preprocessor, you should ensure that both the signed and unsigned modulo operators are followed by white space wherever they appear.

5.5.7 Unary Operators: +, -, ~ and SEG

The highest-priority operators in NASM's expression grammar are those which only apply to one argument. - negates its operand, + does nothing (it's provided for symmetry with -), ~ computes the one's complement of its operand, and SEG provides the segment address of its operand (explained in more detail in Section 5.6).