Another important difference between arrays in C and Java

  • Java stores the length information on array variables:

      int[] A = new int[10];
    
      // After the definition, we can find
      // the length information of array A using:
     
            A.length 

  • C in contrast does not store the length information of arrays:

      int A[10];
    
      // After the definition, there is no way
      //  to find the length information of array A  

Consequence of the length information between arrays in C and Java

  • A consequence of the availability of the length information of arrays in C and Java is:

      • The Java compiler will insert array bound checks when an array element is accessed

      • The C compiler will not do so

  • The Java compiler will always insert this run time array bound check:

              Translated as
    
      a[i] = 0    --->    if ( i < a.length ) 
                             a[i] = 0
    	              else
                             report "index out of bound" error 

Example that shows that Java programs do have array bound checks

  • The following Java program will detect index out of bound when it is run:

       public class array2
       {
          public static void main( String[] args )
          {
       	 double[] a = new double[10];
       	 int    i;
        
       	 for ( i = 0; i < 10; i++ )
       	    a[i] = i;
        
       	 for ( i = 0; i < 30; i++ )
       	    System.out.println( "a[" + i + "] = " + a[i] );
          }
       }

DEMO: demo/C/set/array2.java

Example that shows that C programs do not have array bound checks

  • The following C program will compile and run -- it prints out random values after A[9]:

       int main( int argc, char* argv[] )
       {
          double a[10];
          int    i;
        
          for ( i = 0; i < 10; i++ )
       	 a[i] = i;
        
          for ( i = 0; i < 30; i++ )
       	 printf( "a[%d] = %lf\n", i, a[i] );               
       } 

DEMO: demo/C/set/array2.c

Pros and cons of run time array bound checks

  • Run time array bound checks will help find logic errors in programs

    At the cost of making programs run slower !!!

  • Comment:

      • C is a system programming language

      • A large part of the UNIX/LINUX operating system is written in C

      • Efficiency is an very important consideration in the design of C

      • Therefore:

          • Run time array bound checks is not available in C for efficiency reasons