Comparing Values in Code, Explained with Code Examples

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A comparison is an expression that produces a bool, either true or false, just as 7 + 3 produces a number. A bool converts to a number when printed, so std::cout << (7 > 3) prints 1 and (7 < 3) prints 0. Keep the parentheses, because << binds more tightly than relational operators. Send std::boolalpha to the stream to see words instead.
What is the difference between = and == in C++?
A single = assigns the right-hand value to the left-hand variable, while == compares two values and produces true or false without changing either one. Writing if (x = 5) when you meant if (x == 5) is legal C++, so it compiles and simply stores 5 in x. Reading = as "becomes" and == as "is equal to" helps you catch the slip.
Why does 3 > 2 > 1 evaluate to false in C++?
The expression 3 > 2 > 1 is false because C++ evaluates relational operators left to right, two at a time, instead of reading the chain as in math. First 3 > 2 gives true, which converts to 1, and then 1 > 1 is false. To test whether a value lies between two others, write two separate comparisons and combine them.
Why does 0.1 + 0.2 == 0.3 print false, and how should I compare doubles?
The expression is false because the two double values really differ, by about 5.55 times 10 to the minus 17, so the operator is doing its job. Instead of testing exact equality, ask whether the values are close enough: std::fabs(a - b) < epsilon, where epsilon is a tolerance you choose for your problem. Include the cmath header for fabs.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

C++ Programming
3 credits · NCCRS
Enroll →