Namespaces
Variants
Views
Actions

if statement

From cppreference.com
< cpp‎ | language
Revision as of 10:31, 24 March 2013 by Cubbi (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

Conditionally executes code.

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

Contents

Syntax

if ( Template:sparam ) Template:sparam
if ( Template:sparam ) Template:sparam else Template:sparam

Explanation

Template:sparam shall be an expression, convertible to bool.

If it evaluates to true, control is passed to Template:sparam, Template:sparam (if present) is not executed.

Otherwise, control is passed to Template:sparam, Template:sparam is not executed.

Keywords

if, else

Example

The following example demonstrates several usage cases of the if statement

#include <iostream>
 
int main()
{
    int i = 2;
    if (i > 2) {
        std::cout << "first is true" << '\n';
    } else {
        std::cout << "first is false" << '\n';
    }
 
    i = 3;
    if (i == 3) std::cout << "i == 3" << '\n';
 
    if (i != 3) std::cout << "i != 3" << '\n';
    else        std::cout << "i != 3 is false" << '\n';
}

Output:

first is false
i == 3
i != 3 is false