Feeding Arrays Into Functions, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 6.4 Free with a free account

Feeding Arrays Into Functions

C++ Programming · Chapter 6: ArraysSection 6.4 · lesson 40 of 84video coming soon

← Filling Arrays With Starting DataNext lesson: Multi-Dimensional Arrays →

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

In this lesson

Syntax and behavioral nuances.

  • Write array parameters, and pass the length alongside
  • Predict what a function's changes do to the caller
  • Use const for read-only access
  • Pass vectors and two-dimensional arrays correctly

Transcript

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

Opening Idea

Arrays Break the Single-Value Pattern

Handing a single value to a function is simple. The function gets its own copy, and nothing you do to it affects the original. Arrays don't work that way. The function operates on the caller's actual data, it isn't told how long that data is, and it can't hand a new array back. Those three facts change how functions over arrays are designed. Each of them is a rule to learn here, rather than a mechanism to understand.

Parameter Syntax

Spelling an Array Parameter

A function that averages three named values takes three parameters. A function that averages an array takes two: the array, and how many items it contains. The second one isn't a convenience. Without it, the function has no way to know where the data stops. There are three spellings for an array parameter, and they all mean the same thing. Empty brackets after the name is the usual form. A 5 inside the brackets is ignored, and so is a 100. It's accepted, then disregarded: not enforced, not checked, not learned from. Clang even warns about the mismatch. So prefer the empty form, because the others state something that isn't true. At the call, write the array's name alone. Brackets after it there are an error. And supply the size from a named constant.

Key Rule

Arrays Don't Know Their Length

An array doesn't carry its length with it. Both sides know where the data is, and what type the items are. But only the caller knows how many items there are. Inside the function, there's no property to read, and no built-in way to find out. Whatever the second parameter says is what the function will believe. And a wrong size isn't reported. Passing 8 for an array of 5 compiles cleanly and runs. The loop carries on past the end of the data, reading or writing whatever sits beyond it. So keep the length in a named constant, used both to create the array and to pass it, so there's only one number to get right.

Worked Example

Changes Persist in the Caller

Here's the rule that surprises people who've only passed single values. A function doesn't receive a copy of an array. It works on the caller's data, so any change it makes is still there when the function returns. First, a single value. The function bump sets its own copy to 99, and the caller's value is still 2 afterward. Now the array. Scale all doubles every item. Readings starts as 3, 1, 4, 1, 5. After the call, it's 6, 2, 8, 2, 10: changed by the call.

Perspective

Neither Defect Nor Courtesy

This is neither a defect nor a courtesy. It's simply how arrays are handed over, and once you know it, it's useful. It means a function can fill, sort, or clean up a large set of data without anything being duplicated. It also means a function you expected to be harmless can quietly rearrange your data. And that's what the next idea is for.

Best Practice

Promising Read-Only Access With Const

If a function has no business changing the data, say so in the heading. Marking the parameter const makes the promise part of the declaration, and the compiler holds you to it. This mean function reads every element, which is allowed. It returns 0 for an empty array, and otherwise the total over the size. There are two benefits, and the second is the larger one. The compiler catches an accidental write. And anyone reading the heading alone learns that this function inspects the data without disturbing it. So make const the default for array parameters, and remove it only where the function's job is to change the data. Writing into a const parameter doesn't build. The compiler names the read-only data, and the line, before the program ever runs.

Design Patterns

Modify in Place or Return a Value

A function can't hand a built-in array back to its caller. That constraint leaves exactly two useful designs. Modify in place: the function returns nothing, and its parameter isn't const. Use it for filling, doubling, sorting, or clearing. The answer is the changed data. Compute and return: the parameter is const, and the function returns one value, such as a total, a count, or a position. Fill with is the first kind. Count above is the second: it reads the data, and returns how many items exceed a limit. Here, 4 items exceed 4. After filling with zeros, none do.

Vector Parameters

Value, Reference, and Const Reference

A vector behaves in the ordinary way. It's copied when passed plainly, and it carries its own length, so no second parameter is needed. Passed by value, the vector is copied entirely, and the caller's data is untouched. That's rarely what you want: on a large vector, it's pure waste, and any changes are lost. Passed by reference, with an ampersand, there's no copy, and the function can change the caller's vector. Use it for functions whose job is to modify the contents. And passed by const reference, there's no copy, and no changes are allowed. That's the sensible default for reading and summarizing.

Worked Example

The Silent Missing Ampersand

Here are the same jobs, with vectors. Scale copy takes the vector by value. Scale all takes it by reference, and modifies the caller's vector. Mean takes it by const reference. Now the silent version of the mistake. The by-value version builds, runs, and does nothing observable. It doubles a copy that's discarded the moment it returns. The mean after the first call is still 2. After the by-reference call, it's 4. There's no warning, because the code is perfectly legal. Whenever a vector-modifying function appears to do nothing, check for a missing ampersand first.

Two Dimensions

Fixing Column Counts for Grids

With a grid, only the first dimension may be left empty. Every dimension after it must be written out as a fixed number, and it must match the array being passed exactly. Show grid takes a grid with 4 columns, and a row count. The row count travels as a parameter. The column count is built into the heading. Leaving out both isn't legal, because without the column count, the function can't work out where each row begins. So a grid function is tied to one width. The column number appears twice, in the heading and the inner loop, so declare it as a named constant. And a heading written for 5 columns rejects a 4-column array. The compiler refuses the call: there's no matching function, because marks has four columns, and the heading demands five. The note underneath says it in the compiler's words: there's no conversion from an array with four columns to one with five.

Common Mistakes

Recognizing Errors on Sight

A few mistakes are worth recognizing on sight. A function that appears to do nothing to a vector was passed it by value. Add the ampersand. If the caller's array changed unexpectedly, a parameter that should have been read-only wasn't. Mark it const, and the compiler will find the write. Nonsense values or a crash usually mean the size argument doesn't match the array. Pass the same named constant used to create it. A build failure at the call usually means brackets after the array name. A failure on a grid parameter means a missing or mismatched column count. And if a large vector makes the program sluggish, it's being copied at every call. Take it by read-only reference.

Key Terms

Vocabulary for Array Functions

A few key terms. The size parameter is the separate parameter stating how many items the array holds. Modify in place is a design where the function changes the caller's data, rather than returning new data. Passing by value gives the function its own copy. Passing by reference gives it access to the caller's own object, with no copy made. A read-only reference is a reference marked const. And the fixed column count is the requirement that every dimension after the first be stated.

Key Takeaways

Five Rules to Remember

To summarize. An array doesn't carry its length, so pass the length alongside it, from a named constant. A function's changes to an array persist in the caller, because the array is handed over, not copied. Make array and vector parameters const unless they must change. Modify in place, or return one value. And grid parameters fix every dimension after the first.

Quick Check

Writing a Largest-Value Heading

Here's a quick check. You need a function that finds the largest value in an array of ints. What should its heading look like? Pause, and write it out. Here's one answer: int largest, taking a const int array, and an int size. Const, because it only reads. A size, because the array can't say how long it is. And it returns one value: the compute-and-return design.

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 Feeding Arrays Into Functions

How do you write an array parameter in a C++ function and pass its length?
Use empty brackets after the parameter name and add a separate size parameter, as in double mean(const double a[], int size). An array does not carry its length, so the function trusts whatever size it receives. At the call, write the array name alone, with no brackets, and pass a named constant for the size.
Does a C++ function change the original array that is passed to it?
Yes, a function works on the caller's actual array, not a copy, so its changes remain after it returns. If void scale_all(double v[], int n) doubles each item, an array holding 3, 1, 4, 1, 5 becomes 6, 2, 8, 2, 10. A single int parameter behaves differently, because the function gets its own copy.
Why should I use const for array parameters in C++?
Marking an array parameter const promises the function only reads the data, and the compiler enforces it. An accidental write fails at build time, before the program runs. A reader also learns from the heading alone that the function will not disturb the data. Remove const only when the function's job is to change the array.
Why does my function that takes a vector do nothing to the caller's vector?
The vector was most likely passed by value, so the function changed a copy that was discarded on return. Add an ampersand, as in void scale_all(vector<double>& v), to modify the caller's vector. For read-only work, use a const reference such as const vector<double>& v, which avoids copying and blocks changes.

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 →