Scalar Variables
Scalar variables are used to represent individual fixed-size data objects, such as integers and
pointers. Scalar variables can also be used for fixed-size objects that are composed
of one or more primitive or composite types. D provides the ability to
create both arrays of objects as well as composite structures. DTrace also represents
strings as fixed-size scalars by permitting them to grow up to a predefined
maximum length. Control over string length in your D program is discussed further
in Chapter 6, Strings.
Scalar variables are created automatically the first time you assign a value to
a previously undefined identifier in your D program. For example, to create a
scalar variable named x of type int, you can simply assign it a
value of type int in any probe clause:
BEGIN
{
x = 123;
}
Scalar variables created in this manner are global variables: their name and data
storage location is defined once and is visible in every clause of your
D program. Any time you reference the identifier x, you are referring to
a single storage location associated with this variable.
Unlike ANSI-C, D does not require explicit variable declarations. If you do want
to declare a global variable to assign its name and type explicitly before
using it, you can place a declaration outside of the probe clauses in
your program as shown in the following example. Explicit variable declarations are not
necessary in most D programs, but are sometimes useful when you want to
carefully control your variable types or when you want to begin your
program with a set of declarations and comments documenting your program's variables and their
meanings.
int x; /* declare an integer x for later use */
BEGIN
{
x = 123;
...
}
Unlike ANSI-C declarations, D variable declarations may not assign initial values. You must
use a BEGIN probe clause to assign any initial values. All global variable
storage is filled with zeroes by DTrace before you first reference the variable.
The D language definition places no limit on the size and number
of D variables, but limits are defined by the DTrace implementation and by
the memory available on your system. The D compiler will enforce any of
the limitations that can be applied at the time you compile your program.
You can learn more about how to tune options related to program limits
in Chapter 16, Options and Tunables.