ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.udacity.com/blog/2021/06/understanding-c-logical-operators.html |
| Last Crawled | 2026-04-08 10:23:40 (2 days ago) |
| First Indexed | 2021-06-22 17:28:30 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Understanding C++ Logical Operators | Udacity |
| Meta Description | Logical operators are vital in creating a more dynamic control flow of a program. Read on to learn how to create logical operators and when to use them. |
| Meta Canonical | null |
| Boilerpipe Text | Simple conjunctions like “and” and “or” allow us to connect our ideas — even the most complex ones.Â
These two powerful words can play just as big of a role in the C++ programming language, where they’re used as logical operators.
Logical operators are vital in creating a more complex and dynamic control flow of a program. This article breaks down how to create logical operators and when to use them.
What Are Operators in C++?
Operators are symbols used throughout C++ to perform computations on variables and values.
As you study to become a
C++ developer
, you’ll quickly see that operators play an essential role
in areas such as arithmetic, relational and logical (true or false) statements in code.
C++ uses
Boolean values
to check if relational statements are true or false. Boolean values can only return a 1 (true) or a 0 (false) depending on the result of the comparison. As we’ll see below, we can use these statements in several ways to drive a program towards a specific
outcome.
First, let’s examine
how we can use relational operators
to generat
e true or false outputs.
Relational Operators
Relational operators, as briefly mentioned above, operate on variables with specific values and yield a Boolean result. They use symbols such as
==, !=, <=,
and
>
to check if two operands are the same, different, greater than or less than each other. These operators will output a 1 if the statement is true and a 0 if false.
Logical Operators
Logical operators operate only on Boolean values (or expressions like relational operators that return Boolean values) and yield a Boolean result of their own. The operators used for logical computation in C++Â are
!, &&,
and
||
.
Using Logical Operators in C++?
As we’ll see, logical operators are well suited for checking the validity of two (or more) comparative operations. The operators then output a specific response based on the nature of the operator and whether one or both operands are true. In C++, we often see this in the form of an if/else statement.
Before we can take a closer look at where logical operators often show up in code, we’ll first need to understand the syntax behind them. There are a total of three logical operators:
The ”and” (&&) Operator
The logical “and” operator looks at the operands on either of its sides and returns “true” only if both statements are true. If even just one of the two statements is false, the logical “and” will return false.
Below is a practical example of how we can use the && operator in C++:
#include <iostream>
using
namespace
std
;
int
main
()
{
 Â
cout
<<
"Enter a number: "
;
 Â
int
num {};
 Â
cin
>> num;
 Â
if
(num >
0
&& num <=
10
)
   Â
cout
<<
"Your number is between 1 and 10"
;
 Â
else
   Â
cout
<<
"Your number is not between 1 and 10"
;
 Â
return
0
;
}
Above, we ask the user to provide a number. Our logical “and” operator checks to see if the number is greater than 0 and also less than or equal to 10. If both of these statements are true, the number must fall between 1 and 10, and we can output that this is the case.
If a number of 0 or less, or a number greater than 10 is entered, the program will declare the result “false,” negating the if statement and instead outputting that the number is not between 1 and 10.
The “or” (||) Operator
The logical “or” operator works similarly to the ”and” operator above. The difference is that “or” will return “true” if either the left or the right operand is true. The || operator will only return a false value if both operands are false.
Consider a scenario where picking one of two lucky numbers between 1 and 10 in a game will win us a prize. For this example, we’ll set the lucky numbers to four and eight. We’ll need to create a program in C++ to check for winners:
#include <iostream>
using
namespace
std
;
int
main
() {
 Â
cout
<<
"Enter a number: "
;
 Â
int
num {};
 Â
cin
>> num;
 Â
if
(num ==
4
|| num ==
8
)
   Â
cout
<<
"You chose a winning number!"
;
 Â
else
   Â
cout
<<
"Sorry, better luck next time."
;
 Â
return
0
;
}
When a user comes to play our game, they’re asked to input a number. If they correctly guess either four or eight, they’re notified that they chose a winning number. If the user inputs any other integer value, they’ll have to try again some other time.
The “not” (!) Operator
The “not” logical operator is used to convert a value from true to false, or from false to true. Similarly, if an operand evaluates to true, a logical “not” would cause it to evaluate to false. If an operand evaluates to false, its logical “not” equivalent would be true.
The following example reveals one possible use for the logical “not” operator:
#include <iostream>
using
namespace
std
;
int
main
()
{
 Â
cout
<<
"Enter a number: "
;
 Â
int
x {};
 Â
cin
>> x;
 Â
 Â
if
(!x ==
0
)
   Â
cout
<<
"You typed a number other than 0"
;
 Â
else
   Â
cout
<<
"You typed zero"
;
 Â
return
0
;
}
This program is set up to return true any time the variable
x
is not zero. The
if statement
checks to see if
x
is equal to 0, which will return false for every number but zero. The
!
operator flips the result from false to true, causing the program to output the true result of the
if
statement:
Enter a number: 786
You typed a number other than 0
When using a logical “not” operator, it’s important to remember that it has a very high level of precedence in C++. The logical “not” executes before comparative operators like equals (
==
) and greater than (
>
). When coding with a logical “not”, the programmer must ensure that the program is set up to execute operators in the correct order.
In the below example, we see how failing to do so leads to a problem::
#include <iostream>
using
namespace
std
;
int
main
()
{
 Â
int
num1 =
3
;
 Â
int
num2 =
11
;
 Â
if
(!num1 > num2)
   Â
cout
<< num1 <<
" is not greater than "
<< num2;
 Â
else
   Â
cout
<< num1 <<
" is greater than "
<< num2;
 Â
return
0
;
}
In this example, the program will first execute the logical ! before performing the comparison. In doing so, the program erroneously returns the following:
3 is greater than 11
To set things right, we’ll need to revise our if statement to the following:
if (!(
num1
> num2))
This way, the program performs the relational operation first, followed by the logical “not” to lead us to the correct output.
The Truth Table of Logical Operations
No matter how extensive a logical expression, all boil down to a binary true or false value when evaluated.
Considering only the result of an operand “a,” an operand “b” and the logical operator, we can construct the following table that shows the output of a given logical operation.Â
a
b
a && b
a || b
!a
true
true
true
true
false
true
false
false
true
false
false
false
false
false
true
false
true
false
true
true
This table provides a good way to check your work with logical operations. A program that does not return the listed result for the criteria provided will have a mistake that needs resolution.
Bitwise Operators Versus Logical Operators
Bitwise operators look and function similarly to logical operators but operate solely on integer-type values and not Booleans. Bitwise operators compare two integers on a bit-by-bit basis and output a 1 or a 0 depending on the result of the operation.
For the sake of comparison, a bitwise “and” (
&
) looks very similar to a logical “and” (
&&
). Likewise, a bitwise “or” (
|
) follows the same convention as a logical “or” (
||
). Fortunately, the bitwise “not” (
~
) looks significantly different than a logical “not” (
!
).
Mixing up these operators will lead to compilation errors in your program.
Learn C++ With Udacity
Now that you have a better understanding of logical operators, you’re ready to tackle more of what C++ has in store.
At Udacity, we offer an interactive, expert-led program that takes aspiring C++ developers to the next level. You’ll even put your skills to the test by coding five real-world projects.
Enroll in our C++ Nanodegree program today! |
| Markdown | [](https://www.udacity.com/)
- [Learn](https://www.udacity.com/blog/2021/06/understanding-c-logical-operators.html)
- - - #### Schools
- [Artificial Intelligence](https://www.udacity.com/school/artificial-intelligence)
- [Autonomous Systems](https://www.udacity.com/school/autonomous-systems)
- [Business](https://www.udacity.com/school/business)
- [Career Resources](https://www.udacity.com/school/career-resources)
- [Cloud Computing](https://www.udacity.com/school/cloud-computing)
- [Cybersecurity](https://www.udacity.com/school/cybersecurity)
- [Data Science](https://www.udacity.com/school/data-science)
- [Executive Leadership](https://www.udacity.com/school/executive-leadership)
- [Programming](https://www.udacity.com/school/programming)
- [Product Management](https://www.udacity.com/school/product-management)
- - #### Popular
- [Data Engineering with AWS](https://www.udacity.com/course/data-engineer-nanodegree--nd027)
- [Introduction to Programming](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000)
- [C++](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213)
- [Business Analytics](https://www.udacity.com/course/business-analytics-nanodegree--nd098)
- [Data Analyst](https://www.udacity.com/course/data-analyst-nanodegree--nd002)
- [All Programs](https://www.udacity.com/catalog/all/any-price/any-school/any-skill/any-difficulty/any-duration/any-type/most-popular/page-1)
- - #### Featured
- [Deep Reinforcement Learning](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893)
- [Computer Vision](https://www.udacity.com/course/computer-vision-nanodegree--nd891)
- [Natural Language Processing](https://www.udacity.com/course/natural-language-processing-nanodegree--nd892)
- [Data Structure and Algorithms](https://www.udacity.com/course/data-structures-and-algorithms-nanodegree--nd256)
- [Sensor Fusion Engineer](https://www.udacity.com/course/sensor-fusion-engineer-nanodegree--nd313)
- [Catalog](https://www.udacity.com/catalog)
- [Business](https://www.udacity.com/blog/2021/06/understanding-c-logical-operators.html)
- [Overview](https://www.udacity.com/enterprise/overview)
- [Resources](https://www.udacity.com/resource-center)
- [Compare Plans](https://www.udacity.com/enterprise/plans)
- [Government](https://www.udacity.com/government/overview)
- [Log In](https://auth.udacity.com/sign-in?next=https://www.udacity.com&_gl=1*sgbi1a*_ga*MjA3MjY4NTQzMy4xNjk1Mzk3ODc0*_ga_CF22GKVCFK*MTY5NTM5OTAwNS4xLjEuMTY5NTM5OTYwNy41OC4wLjA.)
- [Join For Free](https://auth.udacity.com/sign-up?next=https://www.udacity.com&_gl=1*iks2dj*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0NjA1Ni4zLjAuMTcxMjI0NjA1Ni42MC4wLjA.)
Cancel
Select Page
C++ - logical operators - Programming Languages
# Understanding C++ Logical Operators
June 22, 2021\| 5 min read
[Udacity Team](https://www.udacity.com/blog/author/udacity)
[Back](https://www.udacity.com/blog) Understanding C++ Logical Operators
Share
[LinkedIn](https://www.udacity.com/#linkedin "LinkedIn")
[X](https://www.udacity.com/#x "X")
[Facebook](https://www.udacity.com/#facebook "Facebook")
[Email](https://www.udacity.com/#email "Email")
[Share](https://www.addtoany.com/share#url=https%3A%2F%2Fwww.udacity.com%2Fblog%2F2021%2F06%2Funderstanding-c-logical-operators.html&title=Understanding%20C%2B%2B%20Logical%20Operators)
Simple conjunctions like “and” and “or” allow us to connect our ideas — even the most complex ones.
These two powerful words can play just as big of a role in the C++ programming language, where they’re used as logical operators.
Logical operators are vital in creating a more complex and dynamic control flow of a program. This article breaks down how to create logical operators and when to use them.
## What Are Operators in C++?
Operators are symbols used throughout C++ to perform computations on variables and values. As you study to become a [C++ developer](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213), you’ll quickly see that operators play an essential role in areas such as arithmetic, relational and logical (true or false) statements in code.
C++ uses [Boolean values](https://www.udacity.com/2021/06/a-developers-guide-to-c-booleans.html) to check if relational statements are true or false. Boolean values can only return a 1 (true) or a 0 (false) depending on the result of the comparison. As we’ll see below, we can use these statements in several ways to drive a program towards a specific outcome.
First, let’s examine how we can use relational operators to generate true or false outputs.
### Relational Operators
Relational operators, as briefly mentioned above, operate on variables with specific values and yield a Boolean result. They use symbols such as \==, !=, \<=, and \> to check if two operands are the same, different, greater than or less than each other. These operators will output a 1 if the statement is true and a 0 if false.
### Logical Operators
Logical operators operate only on Boolean values (or expressions like relational operators that return Boolean values) and yield a Boolean result of their own. The operators used for logical computation in C++ are !, &&, and \|\|.
## Using Logical Operators in C++?
As we’ll see, logical operators are well suited for checking the validity of two (or more) comparative operations. The operators then output a specific response based on the nature of the operator and whether one or both operands are true. In C++, we often see this in the form of an if/else statement.
Before we can take a closer look at where logical operators often show up in code, we’ll first need to understand the syntax behind them. There are a total of three logical operators:
### The ”and” (&&) Operator
The logical “and” operator looks at the operands on either of its sides and returns “true” only if both statements are true. If even just one of the two statements is false, the logical “and” will return false.
Below is a practical example of how we can use the && operator in C++:
Above, we ask the user to provide a number. Our logical “and” operator checks to see if the number is greater than 0 and also less than or equal to 10. If both of these statements are true, the number must fall between 1 and 10, and we can output that this is the case.
If a number of 0 or less, or a number greater than 10 is entered, the program will declare the result “false,” negating the if statement and instead outputting that the number is not between 1 and 10.
### The “or” (\|\|) Operator
The logical “or” operator works similarly to the ”and” operator above. The difference is that “or” will return “true” if either the left or the right operand is true. The \|\| operator will only return a false value if both operands are false.
Consider a scenario where picking one of two lucky numbers between 1 and 10 in a game will win us a prize. For this example, we’ll set the lucky numbers to four and eight. We’ll need to create a program in C++ to check for winners:
When a user comes to play our game, they’re asked to input a number. If they correctly guess either four or eight, they’re notified that they chose a winning number. If the user inputs any other integer value, they’ll have to try again some other time.
### The “not” (!) Operator
The “not” logical operator is used to convert a value from true to false, or from false to true. Similarly, if an operand evaluates to true, a logical “not” would cause it to evaluate to false. If an operand evaluates to false, its logical “not” equivalent would be true.
The following example reveals one possible use for the logical “not” operator:
This program is set up to return true any time the variable x is not zero. The [if statement](https://www.udacity.com/2021/03/our-guide-to-the-cpp-if-else-statement.html) checks to see if x is equal to 0, which will return false for every number but zero. The \! operator flips the result from false to true, causing the program to output the true result of the if statement:
When using a logical “not” operator, it’s important to remember that it has a very high level of precedence in C++. The logical “not” executes before comparative operators like equals (\==) and greater than (**\>**). When coding with a logical “not”, the programmer must ensure that the program is set up to execute operators in the correct order.
In the below example, we see how failing to do so leads to a problem::
In this example, the program will first execute the logical ! before performing the comparison. In doing so, the program erroneously returns the following:
To set things right, we’ll need to revise our if statement to the following:
This way, the program performs the relational operation first, followed by the logical “not” to lead us to the correct output.
## The Truth Table of Logical Operations
No matter how extensive a logical expression, all boil down to a binary true or false value when evaluated.
Considering only the result of an operand “a,” an operand “b” and the logical operator, we can construct the following table that shows the output of a given logical operation.
| | | | | |
|---|---|---|---|---|
| a | b | a && b | a \|\| b | !a |
| true | true | true | true | false |
| true | false | false | true | false |
| false | false | false | false | true |
| false | true | false | true | true |
This table provides a good way to check your work with logical operations. A program that does not return the listed result for the criteria provided will have a mistake that needs resolution.
## Bitwise Operators Versus Logical Operators
Bitwise operators look and function similarly to logical operators but operate solely on integer-type values and not Booleans. Bitwise operators compare two integers on a bit-by-bit basis and output a 1 or a 0 depending on the result of the operation.
For the sake of comparison, a bitwise “and” (&) looks very similar to a logical “and” (&&). Likewise, a bitwise “or” (\|) follows the same convention as a logical “or” (\|\|). Fortunately, the bitwise “not” (~) looks significantly different than a logical “not” (\!).
Mixing up these operators will lead to compilation errors in your program.
## Learn C++ With Udacity
Now that you have a better understanding of logical operators, you’re ready to tackle more of what C++ has in store.
At Udacity, we offer an interactive, expert-led program that takes aspiring C++ developers to the next level. You’ll even put your skills to the test by coding five real-world projects.
[Enroll in our C++ Nanodegree program today\!](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213)

Udacity Team
[View All Posts by Udacity Team](https://www.udacity.com/blog/author/udacity)
###### Popular Nanodegrees
[Programming for Data Science with Python](https://www.udacity.com/course/programming-for-data-science-nanodegree--nd104)
[Data Scientist Nanodegree](https://www.udacity.com/course/data-scientist-nanodegree--nd025)
[Self-Driving Car Engineer](https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd013)
[Data Analyst Nanodegree](https://www.udacity.com/course/data-analyst-nanodegree--nd002)
[Android Basics Nanodegree](https://www.udacity.com/course/android-basics-nanodegree-by-google--nd803)
[Intro to Programming Nanodegree](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000)
[AI for Trading](https://www.udacity.com/course/ai-for-trading--nd880)
[Predictive Analytics for Business Nanodegree](https://www.udacity.com/course/predictive-analytics-for-business-nanodegree--nd008t)
[AI For Business Leaders](https://www.udacity.com/course/ai-for-business-leaders--nd054)
[Data Structures & Algorithms](https://www.udacity.com/course/data-structures-and-algorithms-nanodegree--nd256)
[School of Artificial Intelligence](https://www.udacity.com/enterprise/artificial-intelligence)
[School of Cyber Security](https://www.udacity.com/enterprise/cybersecurity)
[School of Data Science](https://www.udacity.com/enterprise/data-science)
[School of Business](https://www.udacity.com/enterprise/business)
[School of Autonomous Systems](https://www.udacity.com/enterprise/autonomous-systems)
[School of Executive Leadership](https://www.udacity.com/enterprise/executive-leadership)
[School of Programming and Development](https://www.udacity.com/enterprise/programming)
###### Related Articles
[](https://www.udacity.com/blog/2025/06/how-to-become-an-ai-engineer-in-2025-skills-tools-and-career-paths.html "Link for How to Become an AI Engineer in 2025: Skills, Tools, and Career Paths")
#### [How to Become an AI Engineer in 2025: Skills, Tools, and Career Paths](https://www.udacity.com/blog/2025/06/how-to-become-an-ai-engineer-in-2025-skills-tools-and-career-paths.html "How to Become an AI Engineer in 2025: Skills, Tools, and Career Paths")
Artificial Intelligence is transforming industries around the globe—from improving customer support through chatbots to enhancing healthcare diagnostics...
[AI,](https://www.udacity.com/blog/search/label/ai) [Artificial Intelligence](https://www.udacity.com/blog/search/label/artificial-intelligence)
[](https://www.udacity.com/blog/2025/06/building-robust-mlops-pipelines-from-experimentation-to-production.html "Link for Building Robust MLOps Pipelines: From Experimentation to Production")
#### [Building Robust MLOps Pipelines: From Experimentation to Production](https://www.udacity.com/blog/2025/06/building-robust-mlops-pipelines-from-experimentation-to-production.html "Building Robust MLOps Pipelines: From Experimentation to Production")
Today, machine learning models are no longer confined to research labs; they are integral to business operations,...
[AI,](https://www.udacity.com/blog/search/label/ai) [machine learning](https://www.udacity.com/blog/search/label/machine-learning-2)
[](https://www.udacity.com/blog/2025/06/10-machine-learning-projects-that-will-boost-your-portfolio.html "Link for 10 Machine Learning Projects That Will Boost Your Portfolio")
#### [10 Machine Learning Projects That Will Boost Your Portfolio](https://www.udacity.com/blog/2025/06/10-machine-learning-projects-that-will-boost-your-portfolio.html "10 Machine Learning Projects That Will Boost Your Portfolio")
If you’re diving into machine learning and wondering how to prove what you know, here’s the truth:...
[machine learning](https://www.udacity.com/blog/search/label/machine-learning-2)
[](https://www.udacity.com/blog/2025/06/power-bi-dashboard-examples-inspiration-for-your-next-project.html "Link for Power BI Dashboard Examples: Inspiration for Your Next Project")
#### [Power BI Dashboard Examples: Inspiration for Your Next Project](https://www.udacity.com/blog/2025/06/power-bi-dashboard-examples-inspiration-for-your-next-project.html "Power BI Dashboard Examples: Inspiration for Your Next Project")
As the saying goes, “a picture is worth a thousand words” and the right visuals can transform...
[Data,](https://www.udacity.com/blog/search/label/data) [data science](https://www.udacity.com/blog/search/label/data-science)

#### Company
- [About](https://www.udacity.com/about-us)
- [Why Udacity?](https://www.udacity.com/experience)
- [Blog](https://www.udacity.com/blog?_gl=1*1o0u9yl*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.)
- [In the News](https://www.udacity.com/news)
- [Jobs at Udacity](https://www.udacity.com/jobs?_gl=1*1o0u9yl*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.)
#### Resources
- [Catalog](https://www.udacity.com/catalog)
- [Help and FAQ](https://support.udacity.com/hc/en-us?_gl=1*w7u3yb*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.)
- [Scholarships](https://www.udacity.com/scholarships)
#### Udacity Schools
- [School of Artificial Intelligence](https://www.udacity.com/school/artificial-intelligence)
- [School of Autonomous Systems](https://www.udacity.com/school/autonomous-systems)
- [School of Business](https://www.udacity.com/school/business)
- [School of Cloud Computing](https://www.udacity.com/school/cloud-computing)
- [School of Cybersecurity](https://www.udacity.com/school/cybersecurity)
- [School of Data Science](https://www.udacity.com/school/data-science)
- [School of Product Management](https://www.udacity.com/school/product-management)
- [School of Programming](https://www.udacity.com/school-of-programming)
#### Featured Programs
- [Business Analytics](https://www.udacity.com/course/business-analytics-nanodegree--nd098)
- [SQL](https://www.udacity.com/course/learn-sql--nd072)
- [AWS Cloud Architect](https://www.udacity.com/course/aws-cloud-architect-nanodegree--nd063)
- [Data Analyst](https://www.udacity.com/course/data-analyst-nanodegree--nd002)
- [Intro to Programming](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000)
- [Digital Marketing](https://www.udacity.com/course/digital-marketing-nanodegree--nd018)
- [Self Driving Car Engineer](https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd0013)
#### Only at Udacity
- [Artificial Intelligence](https://www.udacity.com/course/ai-artificial-intelligence-nanodegree--nd898)
- [Deep Learning](https://www.udacity.com/course/deep-learning-nanodegree--nd101)
- [Digital Marketing](https://www.udacity.com/course/digital-marketing-nanodegree--nd018)
- [Flying Car and Autonomous Flight Engineer](https://www.udacity.com/course/flying-car-nanodegree--nd787)
- [Intro to Self-Driving Cars](https://www.udacity.com/course/intro-to-self-driving-cars--nd113)
- [Machine Learning Engineer](https://www.udacity.com/course/aws-machine-learning-engineer-nanodegree--nd189)
- [Robotics Software Engineer](https://www.udacity.com/course/robotics-software-engineer--nd209)
- [](https://www.facebook.com/Udacity)
- [](https://twitter.com/udacity)
- [](https://www.linkedin.com/company/udacity)
- [](https://www.instagram.com/udacity/)
© 2011–2026 Udacity, Inc. "Nanodegree" is a registered trademark of Udacity. © 2011-2024 Udacity, Inc.
We use cookies and other data collection technologies to provide the best experience for our customers.
- [Legal & Privacy](https://www.udacity.com/legal)
- [Site Map](https://www.udacity.com/sitemap)
\[et\_bloom\_locked optin\_id=”optin\_4″\]
### Click below to download your preferred Career Guide
[Web Developer Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/Web_Developer_Career_Guide_2019.pdf)
[Cloud Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/cloud-career-infographic-2019.pdf)
[Data Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/TheCompleteGuidetoLandingaCareerinData_July2018.pdf)
[Robotics Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/UdacityRoboticsJobGuide.pdf)
\[/et\_bloom\_locked\]
Ă—
âś“
Thanks for sharing\!
[AddToAny](https://www.addtoany.com/ "Share Buttons")
[More…](https://www.udacity.com/blog/2021/06/understanding-c-logical-operators.html#addtoany "Show all") |
| Readable Markdown | Simple conjunctions like “and” and “or” allow us to connect our ideas — even the most complex ones.
These two powerful words can play just as big of a role in the C++ programming language, where they’re used as logical operators.
Logical operators are vital in creating a more complex and dynamic control flow of a program. This article breaks down how to create logical operators and when to use them.
## What Are Operators in C++?
Operators are symbols used throughout C++ to perform computations on variables and values. As you study to become a [C++ developer](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213), you’ll quickly see that operators play an essential role in areas such as arithmetic, relational and logical (true or false) statements in code.
C++ uses [Boolean values](https://www.udacity.com/2021/06/a-developers-guide-to-c-booleans.html) to check if relational statements are true or false. Boolean values can only return a 1 (true) or a 0 (false) depending on the result of the comparison. As we’ll see below, we can use these statements in several ways to drive a program towards a specific outcome.
First, let’s examine how we can use relational operators to generate true or false outputs.
### Relational Operators
Relational operators, as briefly mentioned above, operate on variables with specific values and yield a Boolean result. They use symbols such as \==, !=, \<=, and \> to check if two operands are the same, different, greater than or less than each other. These operators will output a 1 if the statement is true and a 0 if false.
### Logical Operators
Logical operators operate only on Boolean values (or expressions like relational operators that return Boolean values) and yield a Boolean result of their own. The operators used for logical computation in C++ are !, &&, and \|\|.
## Using Logical Operators in C++?
As we’ll see, logical operators are well suited for checking the validity of two (or more) comparative operations. The operators then output a specific response based on the nature of the operator and whether one or both operands are true. In C++, we often see this in the form of an if/else statement.
Before we can take a closer look at where logical operators often show up in code, we’ll first need to understand the syntax behind them. There are a total of three logical operators:
### The ”and” (&&) Operator
The logical “and” operator looks at the operands on either of its sides and returns “true” only if both statements are true. If even just one of the two statements is false, the logical “and” will return false.
Below is a practical example of how we can use the && operator in C++:
```
#include <iostream>
using namespace std;
int main()
{
  cout << "Enter a number: ";
  int num {};
  cin >> num;
  if (num > 0 && num <= 10)
    cout << "Your number is between 1 and 10";
  else
    cout << "Your number is not between 1 and 10";
  return 0;
}
```
Above, we ask the user to provide a number. Our logical “and” operator checks to see if the number is greater than 0 and also less than or equal to 10. If both of these statements are true, the number must fall between 1 and 10, and we can output that this is the case.
If a number of 0 or less, or a number greater than 10 is entered, the program will declare the result “false,” negating the if statement and instead outputting that the number is not between 1 and 10.
### The “or” (\|\|) Operator
The logical “or” operator works similarly to the ”and” operator above. The difference is that “or” will return “true” if either the left or the right operand is true. The \|\| operator will only return a false value if both operands are false.
Consider a scenario where picking one of two lucky numbers between 1 and 10 in a game will win us a prize. For this example, we’ll set the lucky numbers to four and eight. We’ll need to create a program in C++ to check for winners:
```
#include <iostream>
using namespace std;
int main() {
 Â
cout << "Enter a number: ";
  int num {};
  cin >> num;
  if(num == 4 || num == 8)
    cout << "You chose a winning number!";
  else
    cout << "Sorry, better luck next time.";
  return 0;
}
```
When a user comes to play our game, they’re asked to input a number. If they correctly guess either four or eight, they’re notified that they chose a winning number. If the user inputs any other integer value, they’ll have to try again some other time.
### The “not” (!) Operator
The “not” logical operator is used to convert a value from true to false, or from false to true. Similarly, if an operand evaluates to true, a logical “not” would cause it to evaluate to false. If an operand evaluates to false, its logical “not” equivalent would be true.
The following example reveals one possible use for the logical “not” operator:
```
#include <iostream>
using namespace std;
int main()
{
  cout << "Enter a number: ";
  int x {};
  cin >> x;
 Â
  if (!x == 0)
    cout << "You typed a number other than 0";
  else
    cout << "You typed zero";
  return 0;
}
```
This program is set up to return true any time the variable x is not zero. The [if statement](https://www.udacity.com/2021/03/our-guide-to-the-cpp-if-else-statement.html) checks to see if x is equal to 0, which will return false for every number but zero. The \! operator flips the result from false to true, causing the program to output the true result of the if statement:
```
Enter a number: 786
You typed a number other than 0
```
When using a logical “not” operator, it’s important to remember that it has a very high level of precedence in C++. The logical “not” executes before comparative operators like equals (\==) and greater than (**\>**). When coding with a logical “not”, the programmer must ensure that the program is set up to execute operators in the correct order.
In the below example, we see how failing to do so leads to a problem::
```
#include <iostream>
using namespace std;
int main()
{
  int num1 = 3;
  int num2 = 11;
  if (!num1 > num2)
    cout << num1 << " is not greater than " << num2;
  else
    cout << num1 << " is greater than " << num2;
  return 0;
}
```
In this example, the program will first execute the logical ! before performing the comparison. In doing so, the program erroneously returns the following:
```
3 is greater than 11
```
To set things right, we’ll need to revise our if statement to the following:
```
if (!(num1 > num2))
```
This way, the program performs the relational operation first, followed by the logical “not” to lead us to the correct output.
## The Truth Table of Logical Operations
No matter how extensive a logical expression, all boil down to a binary true or false value when evaluated.
Considering only the result of an operand “a,” an operand “b” and the logical operator, we can construct the following table that shows the output of a given logical operation.
| | | | | |
|---|---|---|---|---|
| a | b | a && b | a \|\| b | !a |
| true | true | true | true | false |
| true | false | false | true | false |
| false | false | false | false | true |
| false | true | false | true | true |
This table provides a good way to check your work with logical operations. A program that does not return the listed result for the criteria provided will have a mistake that needs resolution.
## Bitwise Operators Versus Logical Operators
Bitwise operators look and function similarly to logical operators but operate solely on integer-type values and not Booleans. Bitwise operators compare two integers on a bit-by-bit basis and output a 1 or a 0 depending on the result of the operation.
For the sake of comparison, a bitwise “and” (&) looks very similar to a logical “and” (&&). Likewise, a bitwise “or” (\|) follows the same convention as a logical “or” (\|\|). Fortunately, the bitwise “not” (~) looks significantly different than a logical “not” (\!).
Mixing up these operators will lead to compilation errors in your program.
## Learn C++ With Udacity
Now that you have a better understanding of logical operators, you’re ready to tackle more of what C++ has in store.
At Udacity, we offer an interactive, expert-led program that takes aspiring C++ developers to the next level. You’ll even put your skills to the test by coding five real-world projects.
[Enroll in our C++ Nanodegree program today\!](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213) |
| Shard | 35 (laksa) |
| Root Hash | 694271346773366035 |
| Unparsed URL | com,udacity!www,/blog/2021/06/understanding-c-logical-operators.html s443 |