DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No More Array Errors (Part I) - Block(3C++)

Accessing Block Elements

The syntax of the operations that access Block elements is identical to the analogous array operations. Moreover, the operations work just as you would expect. This means that you can take a program that uses arrays and, by changing only a few declarations and replacing any code that deals with reallocation, get it to work with Blocks.

For example, the following function was originally written for integer arrays:

       int intcmp( int* s,int* t ){
           int i = 0;
           while(s[i] == t[i] ){
               if( s[i++] == 0 ){
                   return 0;
               }
           }
           return s[i] - t[i];
       }

We can call it with arrays:

       int a[100];
       int b[100];
   

intcmp(a,b);

Or, we can call it with Blocks:

       Block<int> a(100);
       Block<int> b(100);
   

intcmp(a,b);

Moreover, we can change the function declaration to take Block arguments (this would be a prerequisite to using any of the special features that Blocks add to arrays; it is not necessary in this example):

       int intcmp( Block<int>& s, Block<int>& t ){
           int i = 0;
           while(s[i] == t[i] ){
               if( s[i++] == 0 ){
                   return 0;
               }
           }
           return s[i] - t[i];
       }

This compiles and works correctly without changing a single line of the function body!

Furthermore, introducing Blocks adds absolutely no runtime overhead in either version of intcmp(); both versions access Block elements just as efficiently as array elements. In particular, you do not pay for index checking when you use Blocks. This means you can make an out-of-bounds index reference to a Block just as easily as you can to an array, with equally unpredictable results.

You may be interested in understanding how this is possible. If so, read the following subsection. If not, skip to the next section now: you don't need the explanation in order to get the benefits of using Blocks.


Next topic: How this is possible
Previous topic: Other Bells and Whistles

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004