Namespaces
Variants
Views
Actions

if statement

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
if statement
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Conditionally executes code.

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

Contents

[edit] Syntax

if ( expression ) statement_true
if ( expression ) statement_true else statement_false

[edit] Explanation

expression shall be an expression, convertible to bool.

If it evaluates to true, control is passed to statement_true, statement_false (if present) is not executed.

Otherwise, control is passed to statement_false, statement_true is not executed.

[edit] Keywords

if, else

[edit] 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