UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.1 Free with a free account
Comparing Values in Code
C++ Programming · Chapter 4: Decision MakingSection 4.1 · lesson 21 of 84video coming soon
← Planning and Scoping Your First ProjectNext lesson: Layering Multiple Conditions →
In this lesson
How relational expressions produce true or false.
- Treat a comparison as an expression with a value
- Use all six relational operators correctly
- Print bool results as numbers or words
- Avoid the chained, mixed-sign and floating-point traps
Transcript
Everything said in the video, section by section (1,093 words). Read along, or search it.
Opening Idea
Comparisons Produce a Bool Value
Before a program can decide anything, it has to ask a question with exactly two possible answers. That's all a comparison is. It's natural to read 7 greater than 3 as the program asking something. It isn't. It's an expression, exactly as 7 plus 3 is. Arithmetic operators produce numbers. Relational operators produce a bool: one of two values, true or false, and nothing else. Because a comparison produces a value, you can print it, and check it. And that's the habit for later: when a condition misbehaves, pull it out, print it, and see what it actually says.
Operator List
The Six Relational Operators
There are exactly six relational operators. Double equals: is equal to. Exclamation equals: is not equal to. Less than, and greater than, as you'd expect. Then less than or equal to, which is true when either half holds, and greater than or equal to. The two-character operators are single operators, so nothing can come between the characters. The order is fixed: greater than, then equals. And there's no equals, less than, at all.
Visual Model
Operators as Regions Around Five
It helps to see them as regions. Fix the value 5, and ask which values of x make each one true. X less than 5 is true at 4, and false at 5 itself: the boundary is excluded. X less than or equal to 5 includes it. Greater than, and greater than or equal to, are the mirror images on the right. X equals 5 is true only at that one point, and not equal is true everywhere else. Almost every off-by-one fault in a condition is a wrong choice between the two forms. So decide deliberately, each time: does the boundary itself count?
Common Mistake
Assignment Versus Comparison
One equals sign is a completely different operator. A single equals assigns: it puts the value on the right into the thing on the left, and hands that value on. A double equals compares. It examines two values, produces true or false, and changes nothing. Writing x equals 5 where you meant x double equals 5 is legal C++, so it often slips through. It simply stores 5 in x. The habit that protects you: read double equals aloud as, is equal to, and single equals as, becomes. Every single time.
Output Behavior
Printing Bools as One or Zero
Since a comparison produces a value, you can send it straight to the output stream. The result surprises most people the first time. 7 greater than 3, and 7 less than 3, print as 1 and 0, not true and false. A bool converts to a number wherever one is wanted: true to 1, false to 0. The parentheses are necessary, because the output arrows bind more tightly than the relational operators. To see words, send std bool alpha to the stream. It isn't printed. It changes the stream from then on, until std no bool alpha switches it back.
Quick Check
Why Chained Comparisons Go Wrong
In mathematics, writing three values in a chain is ordinary, and means both comparisons hold. In C++, it means something else entirely. Quick check: what does 3 greater than 2 greater than 1 print? Pause, and predict. False. Relational operators run left to right, two at a time. 3 greater than 2 gives true. True becomes 1, and 1 greater than 1 is false. 1 less than 2 less than 3 comes out true, but for the wrong reason: it would be true whatever the middle value was. Clang warns about both. Expressing between, correctly, needs two comparisons combined: the subject of the next lesson.
Hidden Pitfall
Comparing Signed With Unsigned Values
Comparing a whole number with a fractional one is perfectly ordinary: both are brought to a common type first. But one combination genuinely isn't safe. Take a signed int holding minus 1, and an unsigned int holding 1. Is s less than u? The program prints false. When signed and unsigned values of the same width are compared, the signed one is converted to unsigned first, and an unsigned type has no negative region. Minus 1, read as unsigned, is the largest value the type can hold. So the comparison actually performed is about 4.29 billion, less than 1. It's a warning, not an error. It builds, runs, and quietly gives the wrong answer. Turn warnings on, read them, and never mix signedness in a comparison.
Floating Point
Why 0.1 Plus 0.2 Is Not 0.3
For whole numbers, two values that ought to be equal are equal. For fractions, they often aren't. 0.1 plus 0.2, double equals 0.3, prints false. And their difference prints as about 5.55 times 10 to the minus 17. The comparison is doing its job. The values genuinely differ: far too little to matter, far too much to be nothing. The mistake was the question. So ask a better one: are these close enough? The gap you'll tolerate is called an epsilon. Test whether std f abs of the difference falls below it. F abs drops the sign, so either value can be larger.
Design Choice
Equality as a Tolerance Band
Think of equality as a band around a value, not a single point. Its width is a decision about the problem, not a detail of the language. Exact double equals is reliable for whole numbers and characters. A fixed tolerance suits values in a narrow, known range. But the gaps between representable values grow with magnitude, so near a trillion, a billionth is far too fine. A relative tolerance scales with the values, though it's awkward near zero. And where exactness truly matters, avoid the question: hold money as whole cents, and double equals is exact again.
Characters
Comparing Characters by Numeric Code
All six operators work on characters too. A char is a small integer, so comparing two compares their numeric codes. The digits 0 to 9 have consecutive codes, 48 to 57, so subtracting the character 0 from a digit gives its value: 7 minus 0 is 7. Capitals run from 65 to 90, and lowercase from 97 to 122: both alphabetical, but every capital sits below every lowercase letter. A space is 32, below them all. So capital Z less than lowercase a is true, and sorting this way puts Zebra before apple. That's code order, not alphabetical order.
Key Takeaways
Summary of Safe Comparison Habits
To summarize. A relational operator takes two values and produces a bool, which prints as 1 or 0, unless you ask for words with bool alpha. Choose between less than, and less than or equal to, deliberately, by asking whether the boundary should count. Never chain comparisons, and never compare signed with unsigned values. And for floating point, compare within a tolerance, not with double equals. Each comparison answers exactly the question it's given.
Think About It
Is the Operator at Fault?
Here's something to think about. Why does 0.1 plus 0.2, double equals 0.3, give false? And is the comparison operator at fault?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Comparing Values in Code
What does a comparison like 7 > 3 evaluate to in C++, and why does cout print 1 instead of true?
What is the difference between = and == in C++?
Why does 3 > 2 > 1 evaluate to false in C++?
Why does 0.1 + 0.2 == 0.3 print false, and how should I compare doubles?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →