|
| |
Rules for using arrays:
For the examples, assume the declaration:
int myvalues[15];
Rules:
1 - subscripts always start at 0
valid elements then are from myvalues[0] to myvalues[14]
2 - you cannot declare an array with a variable as the number of elements
- int number;
- int yourvalues[number]; // this is illegal
3 - the [ ] operator transforms the array into an element of the array
myvalues is an array, myvalues[3] is an int
4 - never leave the [ ] empty, except in a function header
- myvalues[ ]=0; // this is illegal
- float dothis(int values[]) // this is
legal
- int values []; // this is illegal
5 - omission of the operator [ ] means you are referring to the whole array,
not an element
6 - it is illegal to use the whole array in arithmetic operations
- myvalues=0; // illegal
- myvalues=yourvalues; // illegal
- x=myvalues*3; // illegal
7 - When passing arrays to functions, make sure the function expects an
array and not an element and vice versa
- void dothis(int value[],int n) //
array and integer
- void dothat(int value) // expects an integer
- ...
- dothis(myvalues,5); // is OK for the above
- dothis(myvalues[3], 5); // is not OK
- dothat(myvalues[4]); // is OK
- dothat(myvalues); // is not OK
8 - arrays are always passed by reference and can be modified in functions
|