G2++ Tutorial - G2++(C++)

The Initial Capacity of Strings and Arrays

The initial capacity of a string or array is the number of cells initially allocated to it. Initial capacity should not be confused with maximum size, which is the size at which G2++ truncates fixed size strings and arrays during input or output. Since a string or array can grow up to its initial capacity without reallocation, understanding initial capacity--and how to control it--is the key to writing efficient G2++ programs.

When a number N is used to declare the size of a string or array, the string or array will, in most cases, be created with an initial capacity of N elements. (There are cases where N is ignored insofar as initial capacity is concerned. These cases are discussed in the next section.)

When an asterisk is used, the string or array will be allocated with a default initial capacity of at least ten elements. Why not 100? Whatever number we chose for the default, it would not be right for some programs. We have therefore enhanced the asterisk notation to allow programmers to specify an explicit initial capacity for arbitrary size Strings and arrays.

           *          default initial capacity
           *(N)       default initial capacity of N

To avoid reallocation entirely, always specify a value of N greater than the largest number of elements anticipated. Here's an example:

                   login   *(11)
                           usr     LONG
                           grp     SHORT
                   name    *
                           *(100)  LONG

As before, login, name and proj are arbitrary size strings and arrays, but login will have an initial capacity of at least 11 characters and proj will have an initial capacity of at least 100 longs. name has the default initial capacity of at least 10 characters. The following code is therefore guaranteed not to incur any runtime overhead due to reallocation:

           #include "usr.h"
           USR u;
           u.login="hello world";

Next topic: Pathological Record Definitions
Previous topic: Arbitrary Size Strings and Arrays

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005