UPI Study › Courses › C++ Programming › Free lessons › Lesson 2.4 Free with a free account
Representing Quantities
C++ Programming · Chapter 2: Getting Started with C++Section 2.4 · lesson 11 of 84video coming soon
← Professional Habits: Readability StandardsNext lesson: Named Containers for Data: Variables →
In this lesson
How C++ categorizes numeric information.
- Explain what a type determines
- Compare the integer types, signed and unsigned
- Predict what overflow does in each family
- Know where floating point goes wrong
Transcript
Everything said in the video, section by section (1,591 words). Read along, or search it.
Opening Question
How Memory Knows What Bits Mean
A computer stores nothing but patterns of on and off. So when it finds a pattern in memory, how does it know what that pattern means? It doesn't, on its own. The type tells it. And choosing a type is a decision about meaning, range and precision, all at once.
Key Idea
One Bit Pattern, Three Readings
Memory is uniform. Every location holds the same thing: a fixed number of switches, each on or off. A stored value carries no label saying what it is. Here's one pattern of 32 bits. Read as one whole number, it's 1,094,861,636. Read as one fractional value, it's about 12.14. Read as four separate small values, it's 65, 66, 67 and 68. All three readings are correct. The bits never changed. Only the instruction for reading them did, and that instruction is the type.
Definition
Four Things a Type Settles
A type settles four things at once. How many bits are set aside. Wider storage holds a larger range, and costs more memory. How those bits are read: as a whole number, a number with a fraction, or a truth value. Which range of values fits. Every type has a smallest and a largest value, and nothing outside that range can be stored. And which operations make sense. Dividing two counts and dividing two measurements are different operations, even when they look the same. Because C++ is compiled and statically typed, all of this is settled while the program is built. So the compiler can choose exactly the right machine instructions, with nothing left to decide at run time.
Integer Types
Whole Numbers and Their Widths
Integers are whole numbers: quantities you count, rather than measure. C++ gives you several integer types, and the only difference between them is how many bits each one gets. A char is usually 8 bits, with 256 distinct values. A short is 16 bits, with 65,536 values. An int is usually 32 bits, with about 4.29 billion values. And a long long is 64 bits, with about 18.4 quintillion. Each step doubles the bits, and squares the number of distinct values. But those are the usual widths on a modern desktop. The language guarantees minimums, not exact sizes.
Signed and Unsigned
Same Bits, Different Agreement
Every integer type comes in two versions. A signed type reserves part of its range for negative values. An unsigned type spends the whole range on zero and up. The storage is identical. Eight bits hold 256 patterns either way. Only the agreement about what they mean changes. All zeros is zero either way. Zero followed by seven ones is 127 either way: the largest signed value. But one followed by seven zeros is minus 128 signed, and 128 unsigned. All ones is minus 1 signed, and 255 unsigned. Notice the signed range reaches one further down than up. Zero takes a pattern in the non-negative half, which leaves one extra pattern at the negative end. That holds at every width.
Guarantees
Guaranteed Minimums Versus Usual Sizes
Here's what the language guarantees for each type, next to what you'll usually get. An int is guaranteed at least 16 bits, but is almost always 32, giving roughly plus or minus 2.15 billion. A long is guaranteed 32 bits, but may be 64, depending on the platform. A long long is 64 bits everywhere. Why so many, when one would do? Because the cost is real at scale. Ten million measurements at 64 bits take 80 megabytes. At 16 bits, they take 20. For a handful of values it doesn't matter at all, so the ordinary advice is: reach for int, unless you have a reason not to.
The sizeof Operator
Why Long Differs Across Platforms
These widths are typical, not guaranteed, and that surprises people. C++ runs on everything from tiny controllers to supercomputers, so it fixes minimums, and each type is at least as wide as the one before it. You never have to guess. The sizeof operator reports a type's size in bytes, answered while compiling. Sizeof char is always exactly 1, on every platform, by definition. Short is usually 2, and int usually 4. And look at long. It's 8 bytes on Linux and macOS, but 4 on Windows. That's not a misprint. The same source, built for two common desktops, produces a type of two different widths. So a value that fits on one machine can overflow on the other: a real source of defects.
Practical Tools
Exact Widths and Numeric Limits
When a program depends on an exact width, like a file format, hardware, or network data, say so in the type name. The cstdint header supplies names with the width built in: int8_t, int16_t, int32_t and int64_t. Unsigned versions start with a u. And instead of looking limits up in a table and hoping, ask the machine you're building for. numeric_limits of int, max, gives the largest value an int can hold here. Min gives the most negative.
Prediction Prompt
Pushing Past the Ceiling
Every type has a ceiling and a floor. So what happens when arithmetic pushes past one? The program doesn't stop with an error. Nothing checks by default, because checking every operation would cost time on every operation. For unsigned types, the behavior is defined, and it works like an odometer. An unsigned 8-bit value holds 0 to 255. So, what is 250 plus 10? Pause and predict.
Answer
Unsigned Wraparound Like an Odometer
It gives 4. The true answer, 260, doesn't fit, so it wraps past 255, back through 0. That's 260 minus 256, which is 4. And 0 minus 1 gives 255, because there's no negative side to move into. Nothing is reported. The program simply carries on, with a value nobody intended.
Common Mistake
Signed Overflow and Unsigned Countdowns
Signed overflow is a different, more serious matter. Going past a signed type's range is undefined behavior. The language places no requirement on what happens next. The compiler may assume it never occurs, and optimize on that assumption. The program may wrap, produce nonsense, or misbehave somewhere far away. So never rely on it. Prevent it, with a wide enough type, or a check before the operation. And beware unsigned countdowns. An unsigned value can never drop below zero, so a loop testing for greater than or equal to zero never ends. Unsigned isn't automatically safer. It removes the negative range, but adds wraparound at zero.
Floating Point
Measuring With Significant Digits
Integers count. Floating-point types measure, like a temperature of 36.6 degrees, or a ratio of one third. They borrow from scientific notation: a set of significant digits, and a separate exponent saying where the point goes. That's what floating means. A double uses 64 bits: 1 for the sign, 11 for the exponent, which sets the range, and 52 for the significant digits, which set the precision. That's about 15 to 16 decimal digits. So neighboring values get further apart as numbers grow. Around 1, the gap is tiny. Around a quadrillion, it's one eighth. Precision is a fixed number of significant digits, not a fixed number of decimal places. A float has 32 bits and about 7 digits, for huge volumes of data or graphics. A double is the sensible default, and long double is rarely needed.
Limitation
Why 0.1 Has No Exact Form
Here's the limitation you must know about. Floating-point storage is binary, and a binary fraction can't represent every decimal fraction exactly, just as base ten can't write one third exactly. 0.1 has no exact binary form. What's stored is the nearest value available, which is very slightly larger. So what does 0.1 plus 0.2 give? And is it equal to 0.3? Pause and predict.
Answer and Rules
Tolerance Tests and Money in Cents
It gives 0.30000000000000004, and the equality test is false. Nothing is broken. Every value is the closest one available. But two practical rules follow. Never test floating-point values for exact equality. Check whether the difference is smaller than a tolerance you choose. And never use floating point for money. Hold it as a whole number of the smallest unit, like cents, in a wide integer type.
Two More Types
Bool and the Three Chars
Two more types. Bool holds exactly true or false, and in arithmetic, true counts as 1, and false as 0. Sizeof bool is normally one byte, not one bit. Memory is addressed in bytes, and a machine can't hand back the address of a single bit. Char is, underneath, a small integer. It occupies exactly one byte, guaranteed, which is why it's the unit every sizeof is measured in. Its use for letters is an agreed mapping between small numbers and symbols: 65 is a capital A. And char comes in three distinct types. Plain char may be signed or unsigned, depending on the platform, so don't rely on either. Signed char guarantees the signed reading, and unsigned char, from 0 to 255, is the usual choice for raw bytes.
Rules of Thumb
Sensible Default Types
With this many options, a few defaults save a lot of deliberation. For a count, an index, or any ordinary whole number, reach for int. It's wide enough for almost everything, and fast. For a whole number that might pass about 2 billion, use long long. For any measured or fractional quantity, use double. For a yes-or-no condition, use bool, because it says what's meant. For money, use long long, counted in the smallest currency unit. And for data with a fixed external width, use the exact-width names, like int32_t.
Key Takeaways
Summary and a Platform Puzzle
To summarize. A type fixes how wide a value is and how to read it, which together fix its range and its precision. Integer widths are minimums, not exact sizes, and long differs between common platforms. Unsigned overflow wraps predictably. Signed overflow is undefined, and must be prevented. And floating point is approximate: never test it for exact equality, and never use it for money. Here's something to think about. A program works on Linux, but gives wrong answers for large values on Windows. Nothing in the source changed. Which type would you check first, and why?
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 Representing Quantities
What does a type determine in C++?
What is the difference between signed and unsigned integer types in C++?
What happens when an integer overflows in C++?
Why does 0.1 + 0.2 not equal 0.3 in C++?
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 →