UPI Study › Courses › C++ Programming › Free lessons › Lesson 6.3 Free with a free account
Filling Arrays With Starting Data
C++ Programming · Chapter 6: ArraysSection 6.3 · lesson 39 of 84video coming soon
← One-Dimensional ArraysNext lesson: Feeding Arrays Into Functions →
In this lesson
Initialization approaches and defaults.
- Say exactly what a brace-initialized array holds
- Predict the contents when the list is short
- Explain why uninitialized arrays are dangerous
- Choose how to fill: braces, const, loop, input, or fill
Transcript
Everything said in the video, section by section (1,257 words). Read along, or search it.
Opening Problem
The Gap Between Reserved and Filled
Declaring an array reserves the space. It doesn't put anything sensible in it. That gap, between the room existing and the room being furnished, is the source of a whole family of faults. They produce plausible wrong numbers, rather than obvious failures. And the habit that closes the gap costs two characters of typing.
Core Problem
Uninitialized Arrays Hold Leftover Values
A declaration such as int values, 5, asks for enough room for five whole numbers, and gives that room a name. What it doesn't do is clear the room out. Inside a function, the space holds whatever the machine last left there. Reading it is undefined behavior: anything can print, and the program can misbehave. Add an empty pair of braces, and every element is zero, guaranteed. Two characters separate the two.
Why It Matters
Arbitrary Values Are Worse Than Crashes
Arbitrary is worse than broken. A program that crashes tells you where to look. A program reading arbitrary values usually doesn't crash. It adds them into totals, and reports an answer that's merely wrong. And reading them is undefined behavior, so nothing is promised. The values may even look stable, the same on every run, so the fault seems fixed, then returns when anything else changes.
Exception
Global Arrays Start at Zero
There's one exception worth knowing, so it doesn't confuse you later. An array declared outside every function starts with all elements set to zero, guaranteed. That's a property of where it lives, not of arrays. The arrays you write inside functions get no such promise. So it isn't a reason to leave the braces off. A habit that only works in one of the two places isn't a habit.
Brace List Forms
Listed Values, Then Zeros
The general form is a list of values in braces after the declaration. The compiler assigns them to elements in order, starting at position zero. Then it applies one rule that surprises people the first time: any element the list didn't reach is set to zero. So scores, with all five values listed, holds exactly those five. Counts, with just 3 and 1, holds 3, 1, then three zeros. Cleared, with empty braces, holds five zeros. And inferred, with the size left out and four values listed, has four elements, not five. A list of a single 7 gives 7, then four zeros. Not five sevens. That's the misreading worth guarding against.
Error Cases
Too Many Values Fail to Compile
Supply more values than there's room for, and the compiler refuses. It's an error, not a truncation. And with no braces at all, inside a function, the contents are unknown: reading before writing is undefined behavior.
Size Deduction
Lookup Tables With Empty Brackets
Leaving the size out has a real advantage. When the list is the definition of the data, such as the twelve month lengths, empty brackets mean the length can never disagree with the contents. Adding an entry updates the size automatically, and there's no second number to forget to change. A lookup table like this also replaces a long chain of decisions with a single subscript. The days in month m becomes one expression, rather than twelve comparisons.
Const Arrays
Marking Reference Data Fixed
Some arrays hold reference data: values decided once, by the nature of the problem, that no part of the program has any business altering. Marking those const says so, and the compiler enforces it. Any attempt to write into the array is refused before the program is ever built. The refusal is the smaller half of the benefit. The larger half is what a reader learns at a glance: this data is fixed, and can be relied on wherever it appears.
Const Facts
What Const Does and Does Not Do
What does marking an array constant actually do? Writing to an element becomes an error, caught when the program is built, so the mistake can't reach anybody. It documents intent to the next reader, which is arguably the main benefit. It must still be given its values at the declaration, because there's no later opportunity. It sometimes makes the array faster, but speed isn't the reason to write it. And it doesn't protect against bad subscripts. An index out of range is just as dangerous on a constant array.
Runtime Filling
Loops for Calculated and Input Values
A brace list only works for values you know while writing the program. Everything else is filled after the program starts. From a calculation: a loop sets each element of squares to i plus 1, squared. The last, squares 9, is 100. From the person running the program: a loop prompts for each mark, and reads it into marks, index i. Two details matter more than they look. The size is a named constant, used in both the declaration and the loop bound, so the two can never drift apart. And the prompt prints i plus 1 rather than i, because positions start at zero for the machine, and at one for everybody else.
Same Value Fill
Using std::fill for Non-Zero Starts
Sometimes every element should start as the same non-zero value, such as minus 1, meaning nothing recorded here yet. A loop works perfectly well. And s t d fill says the same thing in one line: the beginning of the array, the end of it, and the value to write. For plain zeros, you don't need it at all. The empty brace list already does that at the declaration, and does it sooner.
Decision Guide
Choosing How to Fill an Array
Choosing an approach comes down to a couple of questions. Do you know the values while writing the program? If so, and nothing will change them, use a brace list marked const. If they'll change, use a plain brace list. If you don't know the values, is it the same value in every element? For zeros, empty braces. For anything else, s t d fill. Otherwise, use a loop, one element per pass, either computed, or read from input with a prompt. A counting or accumulating array always starts with empty braces, because every total must start at zero.
Core Habit
Fill First, Then Think
One habit ties it together. Fill first, then think. Write the braces at the moment you write the declaration, before you've decided how the array will be used. It costs nothing when the array is filled properly later. And it removes the entire family of arbitrary-value faults, in the case where you get distracted halfway through, and the filling loop never arrives.
Key Terms
Initialization Vocabulary Review
A few key terms. Partial initialization is a brace list shorter than the array. The elements it doesn't reach are set to zero. Size deduction means leaving the length out, so the compiler counts the list. Arbitrary contents are what an uninitialized array inside a function holds. A constant array is marked const, so its elements can't be written after the declaration. And a lookup table is a fixed array that replaces a chain of decisions with a single subscript.
Summary and Puzzle
Why the Total Is Wrong
To summarize. A declaration reserves space. It doesn't clear it. A short brace list is completed with zeros, and empty braces are the shortest reliable start for a counting array. Mark reference tables const, and let the list set the length. Fill from calculations or input with a loop. Here's something to think about. This program adds up ten counts before anything has been counted. It prints a total that's simply wrong. Run it twice: here, the total changed between runs. Why is it wrong, and why might it repeat, or not? Pause, and think it through. Here's the answer. The array was never filled, so the loop adds up whatever bits were left in that memory. Reading them is undefined behavior. Those leftovers depend on what ran before, so the total may repeat, or change from run to run. Either way, it's wrong. The fix is the two characters from the start: empty braces, so every count begins at zero. Run it, and the total is zero, as it should be.
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 Filling Arrays With Starting Data
What does int counts[5] = {3, 1}; store in the array?
Why is it dangerous to use an array without initializing it in C++?
What happens if I put more values in the braces than the array can hold?
How do I choose between braces, const, a loop, input, or std::fill to fill a C++ array?
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 →