Namespaces
Variants
Views
Actions

if statement

From cppreference.com
< cpp‎ | language
Revision as of 12:03, 1 May 2013 by Cubbi (Talk | contribs)

Conditionally executes code.

Used where code needs to be executed only if some condition is present.

Contents

Syntax

Template:sparam(optional) if ( Template:sparam ) Template:sparam
Template:sparam(optional) if ( Template:sparam ) Template:sparam else Template:sparam
Template:sparam(C++11) - any number of attributes
Template:sparam - any expression which is contextually convertible to bool or a declaration of a single non-array variable with a brace-or-equals initializer.
Template:sparam - any statement often a compound statement, which is executed if Template:sparam evaluates to true
Template:sparam - any statement often a compound statement, which is executed if Template:sparam evaluates to false

Explanation

If the Template:sparam yields true, Template:sparam is executed.

If the else part of the if statement is present and Template:sparam yields false, Template:sparam is executed.

In the second form of if statement (the one including else), if Template:sparam is also an if statement then that inner if statement must contain an else part as well (in other words, in nested if-statements, the else is associated with the closest if that doesn't have an else)

Notes

If Template:sparam or Template:sparam is not a compound statement, it is treated as if it was:

if(x)
    int i;
// i is no longer in scope

is the same as

if(x) {
    int i;
} // i is no longer in scope

The scope of the name introduced by Template:sparam, if it is a declaration, is the same as the scope of the body of the statements:

if (int x = f()) {
    int x; // error: redeclaration of x
}
else {
    int x; // error: redeclaration of x
}


Keywords

if, else

Example

The following example demonstrates several usage cases of the if statement

#include <iostream>
 
int main()
{
    // simple if-statement with an else clause
    int i = 2;
    if (i > 2) {
        std::cout << i << " is greater than 2\n";
    } else {
        std::cout << i << " is not greater than 2\n";
    }
 
    // nested if-statement
    int j = 1;
    if (i > 1)
        if(j > 2)
            std::cout << i << " > 1 and " << j << " > 2\n";
        else // this else is part of if(j>2), not part of if(i>1) 
            std::cout << i << " > 1 and " << j << " <= 2\n";
 
   // declarations can be used as conditions with dynamic_cast
   struct Base {
        virtual ~Base() {}
   };
   struct Derived : Base {
       void df() { std::cout << "df()\n"; }
   };
   Base* bp1 = new Base;
   Base* bp2 = new Derived;
 
   if(Derived* p = dynamic_cast<Derived*>(bp1)) // cast fails, returns NULL
       p->df();  // not executed
 
   if(auto p = dynamic_cast<Derived*>(bp2)) // cast succeeds
       p->df();  // executed
}

Output:

2 is not greater than 2
2 > 1 and 1 <= 2
df()