7F.3. Treat Parameters as Constants


Call by value

The parameters that we have seen so far are called call-by-value parameters. That just means that, when an expression is passed to a function, the value of the expression is passed. For example, when

  int k = 4;
  int j = sqr(2*k + 3);
is evaluated, expression 2*k+3 is computed and its value, 11, is passed to function sqr.


A standard

The standards for this course require that a function body not change the value of any call-by-value parameter. For example, do not define a function like the following.

  int f(int n)
  {
    …
    n++;
    …
  }
Notice that f  changes the value of n, which C++ allows but the standards for this course do not.


Const parameters

Put a different way, the above standard says that your functions should treat call-by-value parameters as constants. You can enforce that by adding const to parameters. For example, if you define sqr as follows, then the compiler will report an error if you try to change x (possibly in a modified version).

  // sqr(x) returns the square of x.

  int sqr(const int x)
  {
    return x*x;
  }