Implicit Logical Expressions


William Vetterling
03-05-2002, 01:42 PM
It has been the practice in creating the Numerical Recipes in C++ never to use integers or floats as though they were logical expressions, as in the following example:

int i=7;
if (i) printf("Hello, World!");

In C, the meaning of "if(i)" is "if (i != 0)", but in C++ the argument of an if-statement is supposed to be a true logical expression.

With that in mind, we notice a line in simplx.cpp, about 25 lines from the end, that reads:

if (kh >= 1 && l3[kh-1]) {
l3[kh-1]=0;
...etc...


This should read:


if (kh >= 1 && l3[kh-1] != 0) {
l3[kh-1]=0;
...etc...


Although the original code functions properly, we shall change it to the correct form. Let us know if you spot any other examples of improperly formed logical expressions.

mathwiz
03-06-2002, 09:10 PM
in C++ the argument of an if-statement is supposed to be a true logical expression


Well...I don't know about that! Stroustrup 3rd Edition, section 6.3.2, p. 133 says

In an if statement, the first (or only) statement is executed if the expression is nonzero and the second statement (if it is specified) is executed otherwise. This implies that any integer or pointer expression can be used as a condition.

He goes on to give the specific example that "if (x)" means "if (x != 0)".

Stroustrup RULES!

William Vetterling
03-06-2002, 11:47 PM
You win, mathwiz. It is actually Java that demands a logical argument to an if(), and both C and C++ are loosey-goosey. But it still seems to me to be a good programming practice to use a boolean expression in this context, and that has been done consistently in the C++ version of the Recipes (except for the one slip-up noted above, as far as I know).