Declaring Integer Variables

As with ordinary variables, integer variables need not be declared. A variable can simply be given an integer value, and then used in an arithmetic expression.

					$ X=12
					$ ((Y=X * 3))
					$ print $Y
					36
				

However, variables can be explicitly declared integer type by using the typeset –i command. The following example sets the DAYS and MONTHS variables to be integer type:

					$ typeset —i DAYS MONTHS=12
				

There is also another command called integer, which is equivalent to typeset –i. It could be used to declare the DAYS and MONTHS variables like this:

					$ integer DAYS MONTHS=12
				

Variables do not have to be explicitly declared integer type to be used in arithmetic expressions. It may improve performance, but what you really gain with declaring integer variables is stricter type checking on assignments. Integer variables cannot be assigned non-integer values:

					$ integer I=abc
					/bin/ksh: I: bad number
				

Another benefit to declaring integer variables is that arithmetic can be performed directly on integer variables without using the let or ((...)) commands, as long as the integer value is being assigned a value. In other words, you can do this:

					$ integer DAYS="4 + 3"
				

instead of

					$ ((DAYS=4 + 3))
				

or

					$ let "DAYS=4 + 3"
				

This also means that integer variables can be assigned values using arithmetic expressions when declared. Let's try it with the MONTHS variable:

					$ integer MONTHS="36 / 3"
					$ print $MONTHS
					12
				

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.254.118