Relational Operators: Testing Relationships Between Values

UPI Study › Courses › Programming in C › Free lessons › Lesson 4.2 Free with a free account

Relational Operators: Testing Relationships Between Values

Programming in C · Chapter 4: Conditional Logic, Decision Structures, and Practical ApplicationsSection 4.2 · lesson 20 of 787 min · free with a free account

← Workshop: Variables, Data Types, and Formatted OutputNext lesson: Logical Operators and Short-Circuit Evaluation →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Compare values with C's six relational operators and avoid classic traps.

  • Use C's six relational operators and explain why each returns 1 or 0
  • Predict comparisons that mix arithmetic or character codes
  • Compare doubles with fabs and a tolerance instead of ==
  • Recognize the = versus == slip and chained comparison bugs

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (964 words). Read along, or search it.

Opening Question

Is 250 at Least 300

A prize machine at the Starlight Arcade has a sign: need three hundred points to win. Maya has two hundred fifty. Somewhere inside, a program asks one tiny question. Is two fifty at least three hundred? The answer isn't maybe, and it isn't a number of points. It's a flat yes or no. This lesson is about those questions, and about one typing slip that has fooled programmers for decades.

Six Operators

Every Comparison Gives 1 or 0

A relational operator compares two values and says how they relate. C has six of them. Less than, greater than, less than or equal, and greater than or equal. Then two equals signs, for is equal to, and an exclamation mark with an equals sign, for is not equal to. The two-character operators have no space inside, and the equals sign always comes second. Here they are in a program, with Maya's score of 250 and the target of 300. Each result is printed with %d, which prints a whole number. That's exactly what a comparison gives: 1 for true, 0 for false. Build and run it. Less than gives one, and greater than gives zero. Less or equal, one. Greater or equal, zero. Equal, zero, and not equal, one. Two patterns to notice. Equal and not equal are always opposites. And for any two numbers, exactly one of less, equal, and greater is true.

Comparisons as Numbers

Storing and Adding Results

Many languages have a special true-or-false value. Classic C doesn't. A comparison produces a plain int, so you can store it like any other number. Enough is tickets at least fifty, so it's one. Perfect is tickets equal to a hundred, so it's zero. And adding them gives one. In tickets plus ten greater than seventy, C does the arithmetic first, getting seventy-four, and compares second. Relational operators rank below plus and minus. And letters compare by their codes. Capital A is sixty-five, and capital B is sixty-six. But lowercase a is ninety-seven, so it is not less than capital B. A tip: name a stored comparison like a yes-or-no question, such as enough, is empty, or has ticket. Then the line reads almost like English.

Quick Check

Seven Against Seven and Lowercase b

Quick check, with three new comparisons in one line. Seven against seven, twice, and then a lowercase b against a capital B. What does it print? Pause and predict. Build and run it. It prints zero, one, one. Seven is not less than seven, but it is less than or equal to seven. And lowercase b has a bigger code than any capital letter, so b greater than capital B is one.

Comparing Decimals

Using fabs With a Tolerance

Whole numbers are exact, so double equals is safe for them. Decimals are not. A double stores numbers in binary. A value as simple as zero point one has no exact binary form, just as one third has no exact decimal form. So add zero point one and zero point two, and compare the sum with zero point three. Printing seventeen decimals shows the tiny errors. The sum lands a hair above, and the stored zero point three a hair below. So double equals says zero. The fix asks how far apart they are. The fabs function, from math dot h, gives the distance without a minus sign. If that distance is under a tiny tolerance, they're close enough, and the test says one. One millionth is plenty for money, but fit the tolerance to your numbers.

Classic Slip

One Equals Sign in an if

Now the famous slip. One equals sign changes a variable. Two equals signs ask about it. They're one keystroke apart. Sam, the arcade's tester, wanted to ask whether the machine is out of tokens. But he typed only one equals sign. The if statement comes fully in lesson 4.4. For now, read it as: run the next block only when the test is true, meaning not zero. Compile with warnings on, and clang speaks up: using the result of an assignment as a condition without parentheses. Its note says exactly what to do: use double equals, to turn this into an equality comparison. GCC gives a similar warning, in different words. Run it anyway, and it says tokens left, zero, though the machine held ten. The single equals stored zero, and that value, zero, counts as false. Add the second equals sign and rebuild. Now it asks the question, and tokens stays ten. Treat that warning as a bug until proven otherwise.

Math Habit Trap

Chained Comparisons Mislead

One more trap, this time from math class. To check a score is between zero and a hundred, you might chain two comparisons. C reads it from the left. Zero less than or equal to one fifty gives one. And one is always less than or equal to a hundred. So the test answers one, even for a score of one hundred fifty. Clang warns that comparisons like this don't have their mathematical meaning. Asking between takes two separate questions, joined with the AND operator. That's lesson four point three.

Quick Check

Zero Lives Becomes Five

Quick check. In this new program, a player starts with zero lives, and the test has a single equals sign with a five. Which message appears? Pause and predict. Run it. It prints play on, lives five. The single equals stores five in lives, and the value of that assignment is five. Five isn't zero, so it counts as true, and the first block runs. Clang warns here too, exactly as before. So a slipped equals sign can go either way. With zero, the block never runs. With anything else, it always does.

Key Takeaways

Six Operators, Ints and Tolerance

To sum up. C has six relational operators, and each one gives an int: one for true, zero for false. Arithmetic happens before comparison, and letters compare by their codes. Compare doubles with a tolerance, using fabs, never with double equals. And one equals sign changes, two equals signs ask. Compile with warnings on, and take that warning seriously.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

Programming in C 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 Relational Operators: Testing Relationships Between Values

What are the relational operators in C?
C has six relational operators: <, >, <=, >=, == and !=. Each compares two values and gives an int, 1 when true and 0 when false. The two-character operators have no space inside, with the equals sign second. For any two integers, exactly one of less than, equal to and greater than is true, and == and != give opposite results.
What is the difference between = and == in C?
A single = assigns a value, while == compares two values and gives 1 or 0. Writing if (tokens = 0) by mistake stores 0 in tokens, and because the value of that assignment is 0, the condition is false. With if (lives = 5), the value is 5, which counts as true, so the block runs every time. Clang and GCC warn about an assignment used as a condition.
How do you compare two doubles for equality in C?
Compare two doubles by checking whether they are close enough rather than using ==. Use fabs from math.h to get the distance without a sign, as in fabs(a - b) < 0.000001. Because values such as 0.1 are stored as binary approximations, 0.1 + 0.2 == 0.3 gives 0. Choose the tolerance to suit the size and precision of the numbers being compared.
Why does 0 <= score <= 100 not check a range in C?
C evaluates 0 <= score <= 100 from left to right as (0 <= score) <= 100. The first comparison gives 0 or 1, and both are less than or equal to 100, so the whole test is true for any score, including 150. Clang warns that such comparisons lack their mathematical meaning. A correct range test uses two comparisons joined with AND: score >= 0 && score <= 100.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →