Up until this point, you have seen that conditional statements may be either:
Now, try the following:
#include <iostream> int main(); int main() { for ( int i = 10; i; --i ) { std::cout << i << std::endl; } return 0; }
First, i is not a conditional statement, it is simply a variable, so how does this work?
C++ is extremely lax in its interpretation of true and false:
From a programming point of view, however, the conditional statement
if ( x ) { // do something... }
can always be converted to a Boolean-valued operator with one of
if ( x != 0 ) { // if 'x' is an integer type if ( x != 0.0 ) { // if 'x' is a real type if ( x != nullptr ) { // if 'x' is an address
You may object: "But this is one more operator, and therefore slower!" If your compiler does not produce exactly the same output with the following two pieces of code:
// Program 1 #include <iostream> int main(); int main() { double n; double x; std::cout << "Enter an integer: "; std::cin >> n; if ( n != 0 ) { std::cout << "It is non-zero" << std::endl; } else { std::cout << "It is zero" << std::endl; } std::cout << "Enter a real number: "; std::cin >> x; if ( x != 0.0 ) { std::cout << "It is non-zero" << std::endl; } else { std::cout << "It is zero" << std::endl; } return 0; }
// Program 2 #include <iostream> int main(); int main() { double n; double x; std::cout << "Enter an integer: "; std::cin >> n; if ( n ) { std::cout << "It is non-zero" << std::endl; } else { std::cout << "It is zero" << std::endl; } std::cout << "Enter a real number: "; std::cin >> x; if ( x ) { std::cout << "It is non-zero" << std::endl; } else { std::cout << "It is zero" << std::endl; } return 0; }
then the onus is on you to get a real compiler.
When designing the Java language, it was determined that allowing all other types to be interpreted as Boolean values was a significant source of programming errors, and therefore in Java, it is illegal to have anything other than a Boolean-valued variable, a Boolean-valued operator or logical operator in place of a conditional statement in a if, while, do-while or the second argument of a for loop.
For the same reason that Java bans the automatic conversion of either integer values, real values or addresses, it is in your best interest to do so, as well: it is much less likely that a programmer will misinterpret a conditional statement and cause a subsequent error.