Bundling Related Fields With Structs | C++ Programming

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 →

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

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.

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 Bundling Related Fields With Structs

Why does a struct declaration need a semicolon after the closing brace in C++?
A struct declaration is a statement that creates a new type, so it must end with a semicolon, unlike the brace closing a function body. Leaving it out causes errors. Some compilers report a confusing problem on the next thing in the file, often several lines later. If strange errors start just after a struct, check that line first.
How do I initialize a struct with braces in C++, and what happens to members I leave out?
A brace list fills members in declaration order, and any member the list does not reach is zero-filled, or left empty for a string. For example, a Book with only a title leaves the author empty and pages and price at zero. Empty braces make every member empty or zero. Matching is by position, not name.
Can I copy one struct to another with a single assignment in C++?
Yes, one assignment copies every member, even when the struct contains arrays or strings. This differs from plain arrays, which cannot be assigned to each other. After spare = original, changing spare.price to 195 leaves original.price at 250, because the two variables are completely independent copies.
Should I pass a struct to a function by value, by reference, or by const reference?
Use a const reference to read a struct, since no copy is made, and a plain reference to modify the caller's struct in place. Passing by value copies the whole struct, which is rarely what you want for anything large. A function can also return a struct by value, which is safe and bundles several related results together.

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 →