Olba12 Olba12 -5 years ago 100
Java Question

The difference between arrays in Java and C

In my book there is an example which explains the differences between arrays in Java and C.

In Java we can create an array by writing:

int[] a = new int[5];

This just allocates storage space on the stack for five integers and we can access them exactly as we would have done in Java

int a[5] = {0};
int i;
for (i = 0, i < 5; i++){
printf("%2d: %7d\n", i, a[i]);

Then the author says the following

Of course our program should not use a number 5 as we did on several places in the example, instead we use a constant. We can use the C preprocessor to do this:

#define SIZE 5

What are advantages of defining a constant SIZE 5?

Answer Source

Using a named constant is generally considered good practice because if it is used in multiple places, you only need to change the definition to change the value, rather than change every occurrence - which is error prone.

For example, as mentioned by stark in the comments, it is likely that you'll want to loop over an array. If the size of the array is defined by a named constant called SIZE, then you can use that in the loop bounds. Changing the size of the array then only requires changing the definition of SIZE.

There is also the question of whether #define is really the right solution. To borrow another comment, from Jonathan Leffer: see static const vs #define vs enum for a discussion of different ways of naming constants. While modern C does allow using a variable as an array size specifier, this technically results in a variable-length array which may incur a small overhead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download