UPI Study › Courses › C++ Programming › Free lessons › Lesson 9.1 Free with a free account
Bundling Related Fields With Structs
C++ Programming · Chapter 9: Structs, Classes, and File StreamsSection 9.1 · lesson 59 of 84video coming soon
← Breaking Tasks Into FunctionsNext lesson: Making Structs Smarter →
In this lesson
How structs organize data.
- Declare a struct, and explain its closing semicolon
- Create one, and read or write its members
- Initialize with braces; copy a whole struct at once
- Pass structs to functions; use an array of them
Transcript
Everything said in the video, section by section (1,159 words). Read along, or search it.
Opening Idea
Four Facts About One Book
Some values belong together. A title, an author, a page count, and a price are four separate facts about one book. Keeping them in four separate variables works, right up until you have two books. Then every operation has to remember to carry all four, in step, without dropping one. A struct makes the grouping official: one name, one variable, four fields traveling together.
Why Group
Parallel Arrays Drift Out of Sync
Without a way to group values, related facts get stored in separate arrays, lined up so that position 2 in each refers to the same book. That works, and it fails in a particular way. Nothing in the program says the arrays belong together. So nothing stops one being sorted on its own. Watch. Sorting just the titles gives Godaan, Kanthapura, Malgudi, but the page counts stayed put. Godaan now claims 258 pages, and Kanthapura 442. The data is wrong, and there's no error to point at. Hold the same information as one array of bundles, and sorting moves whole books. The facts can't separate, because they were never stored apart. The gain isn't fewer keystrokes. A rule you were enforcing by being careful, these always refer to the same book, becomes a property of the data itself.
Declaration
Declaring a Type With Members
A struct declaration describes a new kind of thing, by listing the values it's made of. Each value is a member, declared exactly as an ordinary variable would be. A book has a title, an author, pages, and a price. Two things about that declaration matter more than they look. First, it creates a type, not a variable. No storage exists yet, and nothing holds a title. Second, the semicolon after the closing brace is required, unlike the brace closing a function body. Leave it out, and the compiler objects, as shown. Some compilers don't say so plainly: they report something puzzling about the next thing in the file, often several lines down. So a cascade of strange errors, starting just after a struct, is worth one look at that line first.
Member Access
Reaching Members With the Dot
Once the type exists, variables of it are declared like any other. Individual members are reached with a dot, which reads naturally from left to right. Novel dot pages is the pages of novel. Here, novel's title, author, pages and price are set one by one, and then the title and pages are printed. A member behaves exactly like a variable of its own type. Pages can be added to, compared, or passed to a function. The title can be appended to, or searched. There's no special vocabulary for members. The dot simply says which variable you mean.
Initialization
Brace Lists and Zero-Fill
Assigning members one at a time is tedious. A brace list fills them in declaration order. And the same zero-fill rule as arrays applies. Anything the list doesn't reach is set to zero, or to empty for a string. So a full list sets all four. A list with only a title leaves the author empty, and pages and price at zero. Empty braces make every member empty or zero. Run it: the novel has 333 pages, the draft has 0, its author is empty, and the blank book's price is 0.
Common Mistakes
Uninitialized Numbers and Swapped Order
Brace lists come with two traps. A plain declaration inside a function leaves the numeric members holding arbitrary values, exactly as an uninitialized array does. Reading them is undefined behavior: there is no safe value to expect. The string members are fine, because a string arranges its own empty starting state. So a struct can be half-initialized, in a way that's invisible until a number comes out wrong. The second trap is order. A brace list is matched to members by position, not by name. Swap two members of the same type in the list, and the compiler accepts it happily. The book simply ends up with the author in the title: the second line of the run prints Amitav Ghosh. When a struct has several members of one type, checking the list against the declaration is worth the ten seconds.
Copying
One Assignment Copies Everything
A single assignment copies every member. That's worth stating explicitly, because arrays don't behave this way. An array can't be assigned to another array. Here, spare equals original copies all four members. Then spare's price is changed to 195. The original's price is still 250. Afterward, the two variables are entirely independent. And a struct can be copied whole like this, even when it contains arrays or strings.
Functions
Passing and Returning Whole Structs
Because a struct is a single value, it travels to and from functions like any other. The choice between copying and linking is exactly the one you already know. Copy small read-only things, link large ones, and link anything you intend to modify. Print book takes a const reference. It reads the book, and no copy is made. Apply discount takes a plain reference, because it modifies the caller's book in place. Taking a book by value copies the whole struct, which is rarely what you want. And make book returns a whole book to the caller. It starts with an empty book, fills in the title and pages, and returns it by value, which is safe. Run it: the price goes from 399 to 359.1, after a 10 percent discount.
Multiple Results
Returning a Struct Instead of References
This is the cleaner answer to several results. Returning a few related values used to mean reference parameters, with the caller declaring variables in advance. If the values genuinely belong together, a small struct returned by value says so, keeps the call usable inside an expression, and gives each value a name at both ends. The reference parameter remains the right tool when the results really are unrelated.
Struct Arrays
Subscript First, Then Dot
An array of structs is declared exactly as any array is, here three books on a shelf. It's reached with a subscript followed by a dot: first say which one, then say which part of it. The loop prints each book's title and author. Shelf one dot price reads in two steps. The subscript picks the whole record, Godaan. Then the dot picks one member of it, the price. It prints 399. The order can't be swapped. There's no shelf dot price, index one, because the array holds books, and only a book has a price.
Quick Check
Predicting a Copied Point
Quick check, with a new struct. A point is braced with just 3, a second point is copied from it, and then the copy's y is set to 7. What does the program print? Pause and predict. It prints 3, 0, 7. The brace list never reached a's y, so it was zero-filled. And b is a separate copy, so setting b's y leaves a's y at zero.
Key Takeaways
Struct Essentials in Review
To summarize. A struct declares a new type, and its declaration ends with a semicolon. The dot reaches a member, and members behave like ordinary variables. Empty braces zero-fill a struct, and a brace list matches members by position, not name. A single assignment copies the whole struct. Pass a const reference to read a struct, and a plain reference to modify it.
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 Bundling Related Fields With Structs
Why does a struct declaration need a semicolon after the closing brace in C++?
How do I initialize a struct with braces in C++, and what happens to members I leave out?
Can I copy one struct to another with a single assignment in C++?
Should I pass a struct to a function by value, by reference, or by const reference?
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 →