if - legal expressions
The expressions that an
if statement
evaluates must either be convertible to an
int:
if(1)
cout << "1 is equivalent to true\n";
or to a
char:
if('f')
cout << "\'f\' is equivalent to true\n";
or to a floating-point value:
if(3.5)
cout << "3.5 is equivalent to true\n";
or to a pointer:
int *p, a;
a = 4;
p = &a;
if(p)
cout << "p (the address it contains) is equivalent to true\n";
Any expression evaluating to such values is legal for an
if statement, including assignments:
if(int d = 4 * 7)
cout << "d\'s value is " << d << endl;
and functions:
if(by10(5) > 30)
cout << by10(5) << " is greater than 30\n";
Further, an alternative statement can be executed in case the expression
evaluated by the if statement evaluates to false:
if(a > 0)
cout << "a is greater than 0\n";
else
cout << "a is smaller than, or equal to, 0\n";
else precedes the alternative statement.
Such a statement can also be another
if statement:
if(b > 0)
cout << "b is greater than 0\n";
else if(b < 0)
cout << "b is smaller than 0\n";
else
cout << "b is equal to 0\n";
Example
#include <iostream>
using namespace std;
int by10(int x)
{
return x * 10;
}
int main()
{
if(1)
cout << "1 is equivalent to true\n";
if(3.5)
cout << "3.5 is equivalent to true\n";
if('f')
cout << "\'f\' is equivalent to true\n";
int *p, a;
a = 4;
p = &a;
if(p)
cout << "p (the address it contains) is equivalent to true\n";
if(by10(5) > 30)
cout << by10(5) << " is greater than 30\n";
if(int d = 4 * 7)
cout << "d\'s value is " << d << endl;
if(a > 0)
cout << "a is greater than 0\n";
else
cout << "a is smaller than, or equal to, 0\n";
int b = 0;
if(b > 0)
cout << "b is greater than 0\n";
else if(b < 0)
cout << "b is smaller than 0\n";
else
cout << "b is equal to 0\n";
}
Output
3
5
3