Pass by Value vs. Pass by Reference in C | Programming in C

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

← Variable Storage Classes in CNext lesson: Recursion: Functions That Call Themselves →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

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.

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?
C passes every argument by value: the function receives a copy in a new parameter variable. Changing the parameter does not change the caller's variable, so an add_bonus function that adds 10 to its copy leaves main's tokens at 20. Passing an address is often called pass by reference, but strictly C passes a copy of the address, which still leads to the original variable.
Why doesn't my swap function work in C?
A swap function with plain int parameters exchanges its own copies, which disappear when it returns, so the caller's variables never change, and the compiler gives no warning. To fix it, declare the parameters as int *x and int *y, use *x and *y inside, and call swap(&a, &b). Then a temporary holds *x, *x takes *y, and *y takes the temporary.
How can a C function return two values?
A function can return only one value directly, so pass the addresses of variables for the extra results. A function that splits 47 tokens into 5-token games can take total and per_game as ordinary values and games and left as int pointers, then set *games = total / per_game and *left = total % per_game. Calling it with &games and &left gives 9 games and 2 tokens left.
Should a C function return a result or change a variable through a pointer?
Return the result when the function produces one answer, and let the caller store it, as in tokens = add_bonus(tokens). Use a pointer parameter when the function must change the caller's variable or hand back two or more results. Plain values suit inputs the function only reads, since the function gets a copy and cannot change the original by accident.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →