6.1 if Statement

I l @ ve RuBoard

The if statement allows you to put some decision-making into your programs. The general form of the if statement is:

 if (   condition   )   statement;   

If the expression is true (nonzero), the statement is executed. If the expression is false (zero), the statement is not executed. For example, suppose you are writing a billing program. At the end, if the customer owes nothing or if he has credit (owes a negative amount), you want to print a message. In C++ this is written:

 if (total_owed <= 0)      std::cout << "You owe nothing.\n"; 

The operator <= is a relational operator that represents less than or equal to. This statement reads, "If the total_owed is less than or equal to zero, print the message." The complete list of relational operators is found in Table 6-1.

Table 6-1. Relational operators

Operator

Meaning

<=

Less than or equal to

<

Less than

>

Greater than

>=

Greater than or equal to

==

Equal

!=

Not equal

Multiple relational expressions may be grouped together with logical operators . For example, the statement:

 if ((oper_char == 'Q')  (oper_char == 'q'))     std::cout << "Quit\n"; 

uses the logical OR operator ( ) to cause the if statement to print "Quit" if oper_char is either a lowercase "q" or an uppercase "Q". Table 6-2 lists the logical operators.

Table 6-2. Logical operators

Operator

Usage

Meaning

Logical OR ( )

( expr1 ) ( expr2 )

True if expr1 or expr2 is true

Logical AND ( && )

( expr1 ) && ( expr2 )

True if expr1 and expr2 are true

Logical NOT ( ! )

! ( expr )

Returns false if expr is true; returns true if expr is false

Multiple statements after the if may be grouped by putting them inside curly braces ({ }). For example:

 if (total_owed <= 0) {      ++zero_count;      std::cout << "You owe nothing.\n"; } 

For readability, the statements enclosed in curly braces are usually indented. This allows the programmer to quickly tell which statements are to be conditionally executed. As you will see later, mistakes in indentation can result in programs that are misleading and hard to read.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net