UPI Study › Courses › Programming in C › Free lessons › Lesson 6.5 Free with a free account
Pass by Value vs. Pass by Reference in C
Programming in C · Chapter 6: Functions, Scope, Storage Classes, and RecursionSection 6.5 · lesson 37 of 786 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Recursion: Functions That Call Themselves →← Variable Storage Classes in CNext lesson: Recursion: Functions That Call Themselves →
In this lesson
Why C functions get copies, and how addresses let them change variables.
- Explain why changing a parameter does not change the caller's variable
- Return a single result and store it in the caller
- Write a swap function using address parameters with & and *
- Use address parameters to hand back two or more results
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (853 words). Read along, or search it.
Opening Analogy
Photocopy Versus Original
Imagine handing a friend your homework to look over. Give them a photocopy, and they can scribble all over it. Your original stays clean. Give them the original, and every scribble lands on your page. Functions in C get the photocopy by default. That's safe, but it surprises almost every beginner who writes a function to change a variable.
Pass by Value
The Parameter Is a New Box
When you write add_bonus of tokens, C reads the number inside tokens, and puts a copy of it into the function's parameter. The parameter is a brand-new box, with its own name and its own space. This is called pass by value: only the value travels. Priya's add_bonus should give a player 10 extra tokens. Run it, and watch the balance. Before the call, 20. Inside, the function's box holds 30. But back in main, the balance is still 20. The function added 10 to its own copy, and when it ended, the copy disappeared. Two boxes that just happen to share a name.
Returning a Result
Storing What the Function Returns
If a function only needs to hand one answer back, use return, and store the result. Change void to int, and return tokens at the end. Then in main, write tokens equals add_bonus of tokens. Build and run. Now main's tokens is 30, because main itself stored the answer. Pass by value isn't a flaw. It protects your variables from being changed by accident.
Common Problem
A Swap That Swaps Copies
Here's a classic job: exchange the contents of two boxes, like swapping two cups of juice with the help of a third, empty cup. Sam writes swap the obvious way. temp is the empty cup: it holds x, then x takes y, and y takes temp. Run it. Inside swap, it worked: x is 9, and y is 5. But a and b in main never moved. The function swapped its two photocopies, and threw them away. The compiler printed no warning, because nothing here breaks a rule.
Addresses
Ampersand and Star
To change the caller's box, the function needs to know where that box lives. Every variable sits at an address: a number for its place in memory. Think of it as a house number on a street. C gives you two tiny tools for addresses. Ampersand a means the address of a. You write it at the call. Star x means the box at the address stored in x. You write it inside the function. And a parameter declared int star x holds the address of an int. Pointers get a full lesson in 8.2. This is all you need today.
The Fix
Swapping Through Addresses
Back to Sam's swap. Three changes make it work. First, the parameters become int star x, and int star y. Second, inside the function, each use of x becomes star x, and each use of y becomes star y. Third, the call hands over the addresses: swap of ampersand a, ampersand b. Run it. Before, 5 and 9. Inside, 9 and 5. And after, a is 9 and b is 5. They really moved. The function still got copies, but copies of the addresses. Two copies of a street address lead to the same house.
Familiar Example
Why scanf Needs the Ampersand
You've used this trick since lesson 3.5. In scanf, percent d, ampersand tokens, the ampersand hands scanf the address of tokens. So scanf can put the typed number into your box. Without the ampersand, it would get only a copy, and could never fill the box.
Two Results
Games and Leftover Tokens
A function can return only one value. So what if you need two answers? A player has 47 tokens, and every game costs 5. The arcade wants both how many games they can buy, and how many tokens are left. Priya's function takes total and per_game as ordinary copies: it only reads them. games and left are addresses: it writes into them. In the call, ampersand games and ampersand left give the function permission to fill those two boxes. Run it: 9 games, with 2 tokens left over.
Choosing
Pass a Value or an Address
So which one? C always passes copies. What differs is whether the copy is a value, or an address. Many books call passing an address pass by reference. Strictly, C has no true reference passing: it passes a copy of the address. Pass a value for inputs the function only reads. Pass an address when the function must hand results back, especially two or more.
Quick Check
One Address and One Copy
Quick check. reset takes the address of a score, and a bonus. It sets both to 0. Main passes the address of s, which is 50, and b, which is 7. What does main print? Pause and predict. Build and run: 0, 7. Clang even warns that the parameter bonus is set but not used. That's a clue. Star score followed the address to s, so s became 0. But bonus was only a copy of b. Setting it to 0 changed the copy, and main never saw it.
Key Takeaways
Passing Arguments in Review
To sum up. C passes a copy of each argument, so the function can't touch the original. For one answer, return it, and store the result. To let a function change a variable, write ampersand at the call, and star inside the function. And address parameters let one function fill two or more boxes.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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 All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C 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 Pass by Value vs. Pass by Reference in C
Does C pass arguments by value or by reference?
Why doesn't my swap function work in C?
How can a C function return two values?
Should a C function return a result or change a variable through a pointer?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →