Passing Constant Data to Functions
As you know, if you pass pointers to functions, those functions can change the data to which the pointers point. Since arrays can double as pointers, if you pass an array as a pointer in a function, the function can change your original array. To avoid that, when you pass a copy of your array to the function, mark it as a constant so it can’t be changed. You mark data as constant with the const keyword:
int data[] = {1, 2, 3, 4}; int total = adder(data, sizeof(data)/sizeof(int)); printf("The total is %i\n", total); long adder(const int array[], int number_elements) { long sum = 0; int loop_index; for (loop_index = 0; loop_index < number_elements; loop_index++) sum = sum + array[loop_index]; return sum; }
In this task, we’ll modify the previous task’s code to use constant arrays.
To pass constant arrays to functions:
- Create a new program named functionpassconstarrays.m.
- In functionpassconstarrays.m, enter the code shown in Listing 4.15.
This code creates an array and passes it to a function named adder() whose prototype indicates that it takes constant arrays.
Listing 4.15. Starting functionpassconstarrays.m.
#include <stdio.h> long adder(const int array[], int number_ elements); int main() { int data[] = {1, 2, 3, 4}; int total = adder(data, sizeof(data)/sizeof(int)); printf("The total is %i\n", total); return 0; }
Listing 4.16. The functionpassconstarrays.m program.
#include <stdio.h> long adder(const int array[], int number_ elements); int main() { int data[] = {1, 2, 3, 4}; int total = adder(data, sizeof(data)/sizeof(int)); printf("The total is %i\n", total); return 0; } long adder(const int array[], int number_ elements) { long sum = 0; int loop_index; for (loop_index = 0; loop_index < number_elements; loop_index++) sum = sum + array[loop_index]; return sum; }
- Add the code to create the adder() function, marking the array passed to this function as a constant in the function’s argument list (Listing 4.16).
- Save functionpassconstarrays.m.
- Run the functionpassconstarrays.m program.
You should see the following:
The total is 10