Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

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:

  1. Create a new program named functionpassconstarrays.m.
  2. 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;
    }
  3. 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).
  4. Save functionpassconstarrays.m.
  5. Run the functionpassconstarrays.m program.

    You should see the following:

    The total is 10
  • + Share This
  • 🔖 Save To Your Account