home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeBook TitleSearch this book

B.8. Arithmetic

Starting with ksh93m, the built-in arithmetic facility understands a large percentage of the C language's expressions. This makes the shell more attractive as a full-blown programming language. The following features are available:

Trailing type suffixes
Integer constants can have a trailing U or L suffix to indicate that they are unsigned or long, respectively. While the lowercase versions may also be used, this is not recommended, since it is easy to confuse an l (letter ell) with a 1 (digit one).

C character constants
C single-quoted character constants are recognized. As in C, they act like integer constants. For example:
$ typeset -i c
$ for ((c = 'a'; c <= 'z'; c++))
> do print $c
> done
97
98
99
100
...

Octal and hexadecimal constants
You can use the C format for octal (base 8) and hexadecimal (base 16) constants. Octal constants start with a leading 0, and hexadecimal constants start with a leading 0x or 0X. For example:
$ print $((010 + 1))     Octal 10 is decimal 8
9
$ print $((0x10 + 1))    Hexadecimal 10 is decimal 16
17

Unsigned integer arithmetic
By using typeset -ui, you can create unsigned integers. Regular integers represent both positive and negative numbers. Unsigned integers start at 0, go up to some implementation-dependent value, and then "wrap" around again to 0. Similarly, subtracting 1 from 0 wraps around the other way, yielding the largest unsigned number:
$ typeset -ui u=0
$ let u--
$ print $u
4294967295

C operators and precedence
ksh supports the full set of C operators, with the same precedence and associativity. The operators were presented in detail in Chapter 6 and are summarized again below.

Operator Meaning Associativity
++ -- Increment and decrement, prefix and postfix Left to right
+ - ! ~ Unary plus and minus; logical and bitwise negation Right to left
**

Exponentiation[157]

Right to left
* / % Multiplication, division, and remainder Left to right
+ - Addition and subtraction Left to right
<< >> Bit-shift left and right Left to right
< <= > >= Comparisons Left to right
== != Equal and not equal Left to right
& Bitwise and Left to right
^ Bitwise exclusive-or Left to right
| Bitwise or Left to right
&& Logical and (short circuit) Left to right
|| Logical or (short circuit) Left to right
?: Conditional expression Right to left

= += -= *= /= %= &= ^= <<= >>=

Assignment operators Right to left
, Sequential evaluation Left to right

[157] ksh93m and newer. The ** operator is not in the C language.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.