Const Pointer Parameters - C++ Function

C++ examples for Function:Function Parameter

Introduction

To make sure that the code in the function does not inadvertently modify elements of the array, mark the parameter type with const.

Passing a two-dimensional array to a function

Demo Code

#include <iostream>

double yield(const double values[][4], int n);

int main() {//from  www .  j a va2 s  .com
  double beans[3][4] {
                       { 1.0,   2.0,   3.0,   4.0},
                       { 5.0,   6.0,   7.0,   8.0},
                       { 9.0,  10.0,  11.0,  12.0}
                     };


  std::cout << "Yield = " << yield(beans, sizeof(beans)/sizeof(beans[0]))
            << std::endl;
}

// Function to compute total yield
double yield(const double array[][4], int size)
{
  double sum {};
  for(int i {} ; i < size ; ++i)         // Loop through rows
  {
    for(int j {} ; j < 4 ; ++j)          // Loop through elements in a row
    {
      sum += array[i][j];
    }
  }
  return sum;
}

Result


Related Tutorials