Login    New User    Forgot Password    Help      

IF Statements

GO TO INDEX

IF Statements


The most basic kind of conditional branch in C++ is the if statement. An if statement takes the form:

 
if (expression)
    statement

or

 
if (expression)
    statement
else
    statement2

If the expression evalutes to true (non-zero), the statement executes. If the expression evaluates to false, the else statement is executed if it exists.

The simplest form of an if statement is this:
if (expression)
statement;

The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed. Consider the following example:

if (bigNumber > smallNumber)
bigNumber = smallNumber;
This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the value of smallNumber.
Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following type of branch can be quite large and powerful:
if (expression)
{
     statement1;
     statement2;
     statement3;
}

Here's a simple example of this usage:

if (bigNumber > smallNumber)
{
     bigNumber = smallNumber;
     cout << "bigNumber: " << bigNumber << "\n";
     cout << "smallNumber: " << smallNumber << "\n";
}

This time, if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an informational message is printed. Listing below shows a more detailed example of branching based on relational operators.

// This is my first C++ program

                               

#include < iostream·h>
int main() { int a, b, c; a = 2; b = 3; if(a < b) cout << "a is less than b\n"; if(a == b) cout << "you won't see this\n"; cout << "\n"; c = a - b; cout << "c contains -1\n"; if(c >= 0) cout << "c is non-negative\n"; if(c < 0) cout << "c is negative\n"; cout << "\n"; c = b - a; // c now contains 1 cout << "c contains 1\n"; if(c >= 0) cout << "c is non-negative\n"; if(c < 0) cout << "c is negative\n"; return 0; }

OUTPUT


                                  
a is less than b

c contains -1
c is negative

c contains 1
c is non-negative
                                                    



GO TO INDEX