C Conditions


C++ Conditions

Like Delphi, C++ has two statements for testing conditions: the if statement for testing a small number of conditions and the switch statement for testing a larger number of conditions. Unlike Delphi, the C++ language has a special operator, the conditional (or ternary) operator, which can also be used to test for a condition.

The if Statement

To write an if statement in C++, or in any language for that matter, you need to know which relational operators exist and how they are written. The following table lists all C++ relational operators. Note that the first two operators are also known as equality operators since they are used to test for equality or inequality.

Table 3-9: Relational operators

Relational Operator

Meaning

==

Equality

!=

Inequality

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

Remember that the equality operator in C++ is written with two adjacent equal signs (==), not one. If you use Delphi's equality operator (=) in a C++ expression, you'll be able to compile the application, but you'll also have a bug in your code.

The syntax of the if statement in C++ differs from that in Delphi. The differences are that the condition must always be enclosed in parentheses and that there is no then reserved word that follows the expression:

if (expression)    one_statement; 

If you want to execute more statements in case the expression evaluates to True, place them inside a block:

if (expression) {    statement_1;    statement_2;    statement_n; }

The following listing shows a simple example that tests whether the user entered the number 1.

Listing 3-16: A simple if statement

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i;    cout << "Please enter 1: ";    cin >> i;    if (i == 1)       cout << "Thank you." << endl;    cout << "Press any key to continue...";    getch();    return 0; }
image from book

The if-else Statement

The if-else statement in C++ is different from the Delphi if-then-statement in that it allows the statement before the reserved word else to end with a semicolon. Here's the syntax of the if-else statement:

if (expression)    one_statement_if_true; else    one_statement_if_false; if (expression) {    statement_1;    statement_n; } else {    statement_1;    statement_n; } 

The following listing shows the updated version of the previous example. The updated version uses the if-else statement to output a sad smiley if the user fails to enter the correct value.

Listing 3-17: A simple if-else statement

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i;    cout << "Please enter a number larger than 0: ";    cin >> i;    if (i > 0)       cout << "Thank you." << endl; // note the semicolon    else       cout << ":(" << endl;    cout << "Press any key to continue...";    getch();    return 0; }
image from book

Nested and Multiple if Statements

Multiple if statements in C++ are written exactly as in Delphi, by appending additional if statements after the else statement:

if (expression_1)    statement; else if (expression_2)    statement; else if (expression_3)    statement; else    statement_if_nothing_above_is_true;

The following listing contains a simple example that illustrates nested and multiple if statements in C++.

Listing 3-18: Nested and multiple if statements in C++

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i;    cout << "Please enter a number from 1 to 5: ";    if (i >= 1) {       if (i <= 5) {         if (i == 1)            cout << "One." << endl;         else if (i == 2)            cout << "Two." << endl;         else if (i == 3)            cout << "Three." << endl;         else if (i == 4)            cout << "Four." << endl;         else if (i == 5)            cout << "Five." << endl;       } else         // this is called when i > 5         cout << "You entered an invalid value." << endl;    } else {       // this is called when i < 1       cout << "You entered an invalid value." << endl;    }    cout << "Press any key to continue...";    getch();    return 0; }
image from book

The Conditional (Ternary) Operator

The conditional operator (?:) allows us to perform an if-else test without writing either the if or the else reserved words. Here's the syntax of the conditional operator:

condition ? expression_if_true : expression_if_false;

The conditional operator works by testing the condition and executing the expression_if_true part if the condition evaluates to True. If the condition evaluates to False, only the expression_if_false expression is executed.

The following example shows how to use the conditional operator to find the larger of two numbers.

Listing 3-19: The conditional operator

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i, j;    cout << "Enter the first number: ";    cin >> i;    cout << "Enter the second number: ";    cin >> j;    //                  true : false    int max = i > j ?     i   :   j;    cout << "The larger number is " << max << "." << endl;    getch();    return 0; }
image from book

The conditional operator in the above example replaces the following if-else statement:

int max; if (i > j)    max = i; else    max = j;

Logical (Boolean) and Bitwise Operators

In Delphi, bitwise and Boolean operators are written the same, and the compiler determines which ones we want to use from context. In C++, however, logical and bitwise operators are written differently. The following two tables list the logical and bitwise operators in the C++ language, respectively.

Table 3-10: Logical operators

Syntax

Operator

!

not

&&

and

||

or

Table 3-11: Bitwise operators

Syntax

Operator

&

Bitwise and

|

Bitwise or

^

Bitwise exclusive or

~

Complement (bitwise not)

>>

Shift right

<<

Shift left

When you use the logical operators to construct more complex if statements, don't forget the main pair of parentheses:

int x = 5; if ((x >= 1) && (x <= 10)) {    // x is in the 1..10 range    cout << "OK" << endl; }

If you need to perform a shift left or a shift right operation in the assignment to the cout object, enclose the operation in parentheses. If you don't enclose the shift left operation (<<) in parentheses, the compiler will treat it as the insertion operator (<<) and you'll get an incorrect result:

int x = 2; cout << x << " shl 3 = " << x << 3 <<  endl; // wrong (23) cout << x << " shl 3 = " << (x << 3) <<  endl; // OK (16)

The switch Statement

The switch statement is the C++ version of Delphi's case statement and enables you to test multiple conditions. Here's the syntax of the switch statement:

switch (expression) {   case constant_1: statements;   case constant_2: statements;   default: default_statements; }

The default case serves the same purpose as the else reserved word does in Delphi's case statement: It allows us to execute statements when none of the specific conditions evaluate to True. Like the else part of the case statement in Delphi, the default statement is optional.

In addition to syntax differences, the behavior of the C++ switch statement differs from that in other popular programming languages (except C, of course). The difference lies in the fact that, by default, the C++ switch statement allows execution to fall through all subsequent cases after one of the cases evaluates to True.

To see what fall-through is, take a look at the following example. If it were written in Delphi, it would only display the string "One". In C++, however, the following code displays all three strings because the first case statement evaluates to True, and the execution then falls through all other case statements.

Listing 3-20: Fall-through

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int x = 1;    switch(x) {       case 1: cout << "One" << endl;       case 2: cout << "Two" << endl;       case 3: cout << "Three" << endl;    }    getch();    return 0; }
image from book

To disable fall-through, which is rarely useful and rarely used, end each case statement with the reserved word break, which exits the entire switch statement, and thus effectively skips other case statements:

#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int x = 1;    switch(x) {       case 1: cout << "One" << endl;            break;       case 2: cout << "Two" << endl;            break;       case 3: cout << "Three" << endl;            break;    }    getch();    return 0; }



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

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