Why is different behavior shown for the same code in C and Java?

In C code snippet:

int i;
    double x[10];
    for (i = 0; i <= 10; i++) {
        x[i] = (double) i;
        printf("%f\n", x[i]);
    }

      

outputs the following output:

0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
10.000000

      

However, in Java, the code snippet (the same code) is just syntactically different:

int i;
        double[] x = new double[10];
        for (i = 0; i <= 10; i++) {
            x[i] = (double) i;
            System.out.printf("%f\n", x[i]);
        }

      

outputs the following output:

0.000000
1.000000
2.000000
3.000000
4.000000
5.000000
6.000000
7.000000
8.000000
9.000000
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Array.main(Array.java:14)

      

Why doesn't the C compiler indicate an attempt to access outside the bounds of an array? Did I miss something?

+3


source to share


2 answers


Java has array bounds checking, C does not. In Java, you get a runtime exception when accessing index 10, in C, you get undefined behavior. In this case, you wrote 10.0

to some place where you are also not allowed, but by pure failure the program ended.



Also note that java arrays have a property length

that avoids this error. In the case of C, you can get the length of an array by using the operator carefully sizeof

. But the fact that pointers are often used instead of arrays (for example, when you "pass" an array to a function that takes a pointer to an array element) means that size information is often not available.

+6


source


In C, we can access an element that is not initialized by this variable. In java, we cannot do this. It strictly checks the bounds array.

Java performs bounds checking every time an element in the array is accessed. Boundary checking is when access to an array index is checked against the size of the array - and an exception is thrown if that array index is out of bounds and larger than the size of the array.



C does not perform bounds checking.

0


source







All Articles