UPI Study › Courses › C++ Programming › Free lessons › Lesson 8.1 Free with a free account
Dividing Programs Into Callable Units
C++ Programming · Chapter 8: FunctionsSection 8.1 · lesson 51 of 84video coming soon
← Arrays With Text ProcessingNext lesson: The C++ Standard Library →
In this lesson
The mechanics of functions.
- Name the 4 parts of a function
- Trace control through a call and back
- Tell parameters from arguments
- Declare before use, and state a function's contract
Transcript
Everything said in the video, section by section (1,432 words). Read along, or search it.
Opening Idea
Why Programs Need Named Pieces of Work
Up to now, every program has been one continuous piece of work. That stops scaling long before programs get large, for a reason that has nothing to do with machines: nobody can hold 300 lines in mind at once. A function gives a piece of work a name, a boundary, and a stated contract. So the rest of the program can use it, without knowing how it does its job.
Motivation
Boundaries Make Change Manageable
A program written as one long sequence works perfectly well, right up to the point where you need to change something. Then the questions arrive. Which of these lines are involved in the tax calculation? Are they contiguous? Does anything else depend on the values they leave behind? In one continuous block, none of those questions has a reliable answer, because nothing marks where one idea ends and the next begins. Divide the same work into named units, read order, calculate tax, print receipt, and the calculation doesn't change. What changes is that each piece has a name and a boundary. Each unit can be read on its own, changed without disturbing the others, tried on its own, used more than once, and referred to by name in conversation.
Anatomy
The Four Parts of a Function
Every function has four parts, in this order, and each answers a different question. First, the return type: here, double, the kind of value handed back to whoever called it. Second, the name, rectangle area: how the rest of the program refers to it. A verb phrase reads best. Third, the parameter list: what it must be given, and the type of each. Empty parentheses mean nothing is needed. And fourth, the body: the work itself, between braces, and the only part a caller never has to read. The first line, taken together, is the function's signature. It holds everything a caller needs. The body can be rewritten completely, and as long as the signature and its promise hold, nothing that calls it needs to change.
Call Flow
Four Steps of a Function Call
A call suspends the work in progress, runs the function's body, and then resumes at exactly the point it left. Step one: control leaves the calling code, carrying the arguments 3.0 and 4.5. Step two: the body runs, start to finish. Step three: control returns, handing back the value 13.5. Step four: back in the calling code, the call is now simply the value 13.5. So the assignment stores it, and execution moves on. Control always returns to the point immediately after the call. Never to the top, and never anywhere else. That's what allows the same function to be called from many places.
Terminology
Parameters Versus Arguments Defined Precisely
Parameter and argument are used interchangeably in casual speech, and mean different things precisely. A parameter is a name in the definition, such as double width. It belongs to the function, and exists while the body runs. Whoever writes the function decides it. An argument is a value at the call, such as 3.0. It belongs to the caller, and differs on every call. The return type is decided by the writer, and every caller has to accept it. The returned value is produced by the body, differently for different arguments.
Common Mistake
Arguments Match Parameters by Position
Arguments are matched to parameters by position, not by name. Here, price takes a base and a percent off. Call it with 200 and 10, and the answer is 180. Swap the two arguments, and nothing complains. The function quietly computes the wrong thing, and returns minus 10. Order parameters so the call reads naturally.
Using Results
Calls as Expressions and Discarded Values
A call to a value-returning function is an expression. It can go anywhere a value of that type can go: stored in a variable, printed directly, used in arithmetic, or used in a condition. Writing the call as a statement on its own is legal too. The function runs, produces its value, and the value is discarded. So the last line accomplishes nothing at all. The compiler said nothing, and a run shows no sign of it. If a call's whole purpose was the value it hands back, dropping that value is a fault, and the compiler won't mention it, even with warnings switched on.
Void Functions
Functions That Act Instead of Answer
Some units exist to do something, rather than to work something out: print a heading, clear a display, or write a line to a report. These are written with void as the return type, which says explicitly that there's no result. Greet prints a greeting. If the name is empty, a bare return leaves early, with nothing to hand back. A call to a value-returning function is an expression that stands for a value. A call to a void function is a statement that stands for an action. A value-returning function needs a return on every path, carrying a value. In a void function, return is optional. And you can't assign the result of a void function, because there's nothing to assign.
Declaration Order
Compilers Need Names Before Calls
The compiler reads a file from top to bottom, once, and it can't use a name it hasn't met. Call rectangle area on line 5, and define it on line 9, and the build fails on line 5. Not because the function is missing, but because at that moment, the compiler has never heard of it. Here's the real message. One fix is to define every function before anything that calls it. That works, and puts main at the bottom, where readers don't expect it. The other is to state the signature near the top of the file, and leave the full definition for later. That statement is a declaration, often called a prototype: the signature followed by a semicolon instead of a body. It's a promise, and the definition keeps it. Now the same program builds, and prints 13.5.
Key Distinction
Declaration Versus Definition Compared
A declaration contains the signature and a semicolon. A definition contains the signature and a body in braces. Parameter names are optional in a declaration, because the types alone are enough. They're usually kept anyway, because they document. There can be many declarations, because repeating one is harmless. But there's exactly one definition. If a needed declaration is missing, the build fails at the first call. If the definition is missing, the build fails at the linking stage: the name was promised, and never supplied. Here's that message. So the conventional arrangement is declarations first, then main, the shape of the program and the first thing anybody should read, then the definitions underneath, in any order.
Multiple Returns
Every Path Must Reach a Return
A function may contain several return statements. The first one reached ends the function immediately, and the remaining lines don't run. Size label rejects the impossible case first, an area of zero or less, as invalid. Then it handles each band: small below 50, medium below 200. And it falls through to the remaining case, large. That shape is common, and worth recognizing. One rule governs it. Every path through a value-returning function must reach a return. Leave off the final line, and an area of 500 reaches the closing brace with nothing to hand back. That's undefined behavior, and the compiler only warns, as shown. With the line in place, all four areas give clear answers. Every path returns, so every call has an answer.
Documentation
Writing Down the Function's Promise
A function makes a promise: give me these things, and I'll give you that. Writing the promise down, above the definition, is what lets somebody use the function without reading the body. That's the entire benefit of dividing the program. Purpose answers, is this the thing I'm looking for? Takes answers, what do I hand over, and in what form? Gives answers, what will I get? And assumes answers, what am I responsible for before calling it?
Documentation Detail
Why the Units Line Matters
The units line earns its place. A parameter called width tells you almost nothing. Meters? Centimeters? Pixels? Run it with 2 by 3 meters: 6. Hand it 200 by 300 centimeters and it says 60000. Every calculation is correct, and the answer is out by a factor of ten thousand, with no error. Stating the unit is the cheapest possible protection against faults the compiler can't see.
Quick Check
Swapping Arguments to the Price Function
Quick check. Using the price function from earlier, what do price of 50 and 20, and price of 20 and 50, return? Pause and think. Forty, and ten. Arguments fill parameters by position, so swapping them changes which number is the base, and the compiler says nothing.
Key Takeaways
Summary of Function Essentials
To summarize. A function has a return type, a name, a parameter list, and a body. Control returns to just after the call, with the returned value standing in its place. Arguments fill parameters by position. Declare a function before using it, and define it exactly once. And every path through a value-returning function needs a return.
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 Dividing Programs Into Callable Units
What are the four parts of a function in C++?
What is the difference between a parameter and an argument in C++?
What happens to control when a function is called, and where does it return?
Why does C++ give an error when I call a function before defining it, and how do I fix it?
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 →