0

I implemented fixed-point iteration in C++, and I forgot the return statement:

double fixedpoint(double g(double), double p0, double tol, double max_iter)
{
  double p, error, i = 1;

  do
  {
    p = g(p0);

    error = std::abs(p - p0);
    i++;

    p0 = p;
  } while (i < max_iter && error > tol);

  // No return statement
}

Then I called the function:

/* g(x) = (3x^2 + 3)^(1/4) */
double g(double x)
{
  return pow(3 * x * x + 3, 0.25);
}

int main()
{
  // Test
  double p0 = 1;
  double tol = 1e-2;
  int max_iter = 20;

  double p = fixedpoint(g, p0, tol, max_iter);

  cout << "Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:" << endl;
  cout << "Solution: x = " << setiosflags(ios::fixed) << setprecision(6) << p << endl;
}

and I got the following result:

Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:
Solution: x = 0.005809

In fact, 0.005809 is the value of the error variable (in the fixedpoint function) at the last iteration. Why is that value returned?

I'm using GCC version 7.4.0. (Also I've checked Function not returning value, but cout displays it but it doesn't apply to me.)

Mubaraq Wahab
  • 303
  • 4
  • 14

3 Answers3

4

Why does the C++ function ... return a value?

You declared that the function returns a value. Therefore the function returns a value.

... without a return statement ...

You failed to write a return statement. The behaviour of the program is undefined.

Why is that value returned?

Because the behaviour of the program is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
3

Not returning from a non-void function is undefined behavior. This means anything can happen. One of those things is actually returning a value.

However, this is not behavior you can rely upon. Crashing the program, printing garbage, etc, are all valid behaviors. Turn on compiler warnings, they will tell you that you are making a mistake.

cigien
  • 57,834
  • 11
  • 73
  • 112
3

You defined the function as returning something by declaring it double fixedpoint(...), therefore it WILL return something. Think about it from the perspective of the calling function: It only knows the signature of your function, and will expect to find a double as return value. It doesn't know your implementation, i.e. the fact that you don't specify a return value.

Now if you don't specify what the returns, the return field is usually uninitialized and will contain random data, however the behavior is undefined, which means in principle anything can happen. Turning on compiler warnings (strongly suggested), will warn you about that.

Haatschii
  • 9,021
  • 10
  • 58
  • 95