Neste tutorial, aprenderemos sobre operadores relacionais e lógicos com a ajuda de exemplos.
Em C ++, os operadores relacionais e lógicos comparam dois ou mais operandos e retornam um dos valores true
ou false
.
Usamos esses operadores na tomada de decisões.
Operadores relacionais C ++
Um operador relacional é usado para verificar o relacionamento entre dois operandos. Por exemplo,
// checks if a is greater than b a> b;
Aqui, >
está um operador relacional. Ele verifica se a é maior que b ou não.
Se a relação for verdadeira , ele retorna 1, enquanto se a relação for falsa , ele retorna 0 .
A tabela a seguir resume os operadores relacionais usados em C ++.
Operador | Significado | Exemplo |
---|---|---|
== | É igual a | 3 == 5 nos dá falso |
!= | Diferente de | 3 != 5 nos dá verdade |
> | Maior que | 3> 5 nos dá falso |
< | Menor que | 3 < 5 nos dá verdade |
>= | Melhor que ou igual a | 3>= 5 nos dê falso |
<= | Menos que ou igual a | 3 <= 5 nos dá verdade |
== Operador
O ==
operador igual a retorna
true
- se ambos os operandos são iguais ou iguaisfalse
- se os operandos forem desiguais
Por exemplo,
int x = 10; int y = 15; int z = 10; x == y // false x == z // true
Observação: o operador relacional ==
não é igual ao operador de atribuição =
. O operador de atribuição =
atribui um valor a uma variável, constante, matriz ou vetor. Ele não compara dois operandos.
! = Operador
O !=
operador diferente de retorna
true
- se ambos os operandos forem desiguaisfalse
- se ambos os operandos forem iguais.
Por exemplo,
int x = 10; int y = 15; int z = 10; x != y // true x != z // false
> Operador
O >
operador maior que retorna
true
- se o operando esquerdo for maior que o direitofalse
- se o operando esquerdo for menor que o direito
Por exemplo,
int x = 10; int y = 15; x> y // false y> x // true
<Operador
O operador menor que <
retorna
true
- se o operando esquerdo for menor que o direitofalse
- se o operando esquerdo for maior que direito
Por exemplo,
int x = 10; int y = 15; x < y // true y < x // false
> = Operador
O maior ou igual aos >=
retornos do operador
true
- se o operando esquerdo for maior ou igual ao direitofalse
- se o operando esquerdo for menor que o direito
Por exemplo,
int x = 10; int y = 15; int z = 10; x>= y // false y>= x // true z>= x // true
<= Operador
O menor ou igual aos <=
retornos do operador
true
- se o operando esquerdo for menor ou igual ao direitofalse
- se o operando esquerdo for maior que direito
Por exemplo,
int x = 10; int y = 15; x> y // false y> x // true
Para aprender como os operadores relacionais podem ser usados com strings, consulte nosso tutorial aqui.
Operadores lógicos C ++
Usamos operadores lógicos para verificar se uma expressão é verdadeira ou falsa . Se a expressão for verdadeira , ela retornará 1, enquanto se a expressão for falsa , ela retornará 0 .
Operador | Exemplo | Significado |
---|---|---|
&& | expressão1 && expressão 2 | E lógico. verdadeiro apenas se todos os operandos forem verdadeiros. |
|| | expressão1 || expressão 2 | Logical OR. true if at least one of the operands is true. |
! | !expression | Logical NOT. true only if the operand is false. |
C++ Logical AND Operator
The logical AND operator &&
returns
true
- if and only if all the operands aretrue
.false
- if one or more operands arefalse
.
Truth Table of && Operator
Let a and b be two operands. 0 represents false while 1 represents true. Then,
a | b | a && b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
As we can see from the truth table above, the &&
operator returns true only if both a
and b
are true.
Note: The Logical AND operator && should not be confused with the Bitwise AND operator &.
Example 1: C++ OR Operator
// C++ program demonstrating && operator truth table #include using namespace std; int main() ( int a = 5; int b = 9; // false && false = false cout < b)) << endl; // false && true = false cout << ((a == 0) && (a < b)) << endl; // true && false = false cout < b)) << endl; // true && true = true cout << ((a == 5) && (a < b)) << endl; return 0; )
Output
0 0 0 1
In this program, we declare and initialize two int
variables a and b with the values 5
and 9
respectively. We then print a logical expression
((a == 0) && (a> b))
Here, a == 0
evaluates to false
as the value of a is 5
. a> b
is also false
since the value of a is less than that of b. We then use the AND operator &&
to combine these two expressions.
From the truth table of &&
operator, we know that false && false
(i.e. 0 && 0
) results in an evaluation of false
(0
). This is the result we get in the output.
Similarly, we evaluate three other expressions that fully demonstrate the truth table of the &&
operator.
C++ Logical OR Operator
The logical OR operator ||
returns
true
- if one or more of the operands aretrue
.false
- if and only if all the operands arefalse
.
Truth Table of || Operator
Let a and b be two operands. Then,
a | b | a || b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
As we can see from the truth table above, the ||
operator returns false only if both a
and b
are false.
Example 2: C++ OR Operator
// C++ program demonstrating || operator truth table #include using namespace std; int main() ( int a = 5; int b = 9; // false && false = false cout < b)) << endl; // false && true = true cout << ((a == 0) || (a < b)) << endl; // true && false = true cout < b)) << endl; // true && true = true cout << ((a == 5) || (a < b)) << endl; return 0; )
Output
0 1 1 1
In this program, we declare and initialize two int
variables a and b with the values 5
and 9
respectively. We then print a logical expression
((a == 0) || (a> b))
Here, a == 0
evaluates to false
as the value of a is 5
. a> b
is also false
since the value of a is less than that of b. We then use the OR operator ||
to combine these two expressions.
From the truth table of ||
operator, we know that false || false
(i.e. 0 || 0
) results in an evaluation of false
(0
). This is the result we get in the output.
Similarly, we evaluate three other expressions that fully demonstrate the truth table of ||
operator.
C++ Logical NOT Operator !
The logical NOT operator !
is a unary operator i.e. it takes only one operand.
It returns true when the operand is false, and false when the operand is true.
Mesa da Verdade do! Operador
Seja a um operando. Então,
Exemplo 3: C ++! Operador
// C++ program demonstrating ! operator truth table #include using namespace std; int main() ( int a = 5; // !false = true cout << !(a == 0) << endl; // !true = false cout << !(a == 5) << endl; return 0; )
Resultado
1 0
Neste programa, declaramos e inicializamos uma int
variável a com o valor 5
. Em seguida, imprimimos uma expressão lógica
!(a == 0)
Aqui, é a == 0
avaliado false
como o valor de a é 5
. No entanto, usamos o operador NOT !
no a == 0
. Visto que a == 0
avalia para false
, o !
operador inverte os resultados de a == 0
e o resultado final é true
.
Da mesma forma, a expressão em !(a == 5)
última análise retorna false
porque a == 5
é true
.