Conditional Operator and Function

I came across an interesting question from SICP, and noticed some subtle fact. There is the well-known operator ?: in C++ and several other languages. Now think of a function which takes 3 arguments and performs the conditional operator on them:

1
2
3
4
template <class T>
T ternary(bool a, T b, T c) {
return a ? b : c;
}

Is this function equivalent to ?: itself?

No.
Here is the C++ illustration of the question I mentioned above. The code is simply computing a square root using Newton’s method. See what happens if you use the commented statement to replace the return statement above it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cmath>
using namespace std;
const double eps = 1e-3;
double ternary(bool a, double b, double c) {
return a ? b : c;
}
double newton(double x, double r) {
cout << r << endl;
return abs(r - x / r) < eps ? r : newton(x, (r + x / r) / 2);
// return ternary(abs(r - x / r) < eps, r, newton(x, (r + x / r) / 2));
}
double my_sqrt(double x) {
return newton(x, 1);
}
int main() {
cout << my_sqrt(5) << endl;
return 0;
}

The reason behind this hard-to-foresee behavior is: a function always evaluates all its parameters before execution, while ?: does not.