◐ Shell
clean mode source ↗

if statement - cppreference.com

De cppreference.com

<metanoindex/>

Executa condicionalmente código.

Original:

Conditionally executes code.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Usado onde o código precisa ser executado somente se alguma condição está presente.

Original:

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

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Sintaxe

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

Explicação

expression deve ser uma expressão, conversível a bool.

Original:

expression shall be an expression, convertible to bool.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Se é avaliada como true, o controle é passado para statement_true, statement_false (se houver) não é executado.

Original:

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

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Caso contrário, o controle é passado para statement_false, statement_true não é executado.

Original:

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

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Palavras-chave

if, else

Exemplo

O exemplo seguinte demonstra o uso de vários casos a instrução if

Original:

The following example demonstrates several usage cases of the if statement

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#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';
}

Saída:

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