Nearby lessons

78 of 124

C - Call by Reference

Call by Reference is one of the foundational topics in C programming. This lesson explains Complete Program 4 — Call by Reference (Swap) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Complete Program 4 — Call by Reference (Swap)

In Chapter 9 we saw call by value (a function gets a copy). With pointers we get call by reference: the function receives the address, so it can change the original variable in main().

The classic swap program is THE exam question for call by reference: without pointers, swap cannot change the original values; with pointers, it can.

PointCall by valueCall by reference
What is passedA copy of the valueThe address of the variable
Function can change original?NoYes
SymbolNormal variable& when calling, * in the function
Use forSimple calculationsSwapping, changing variables, big data (no copy)
In simple words: call by reference sends the house address instead of a photocopy — so the function can walk in and change the original. Call by value could never do that.
Example01
CCode Cell
1#include <stdio.h>
2 
3void swap(int *x, int *y) // receives addresses
4{
5 int temp = *x;
6 *x = *y; // change what x points to
7 *y = temp;
8}
9 
10void main()
11{
12 int a = 10, b = 20;
13 
14 printf("Before swap: a=%d b=%d\n", a, b);
15 swap(&a, &b); // pass addresses
16 printf("After swap : a=%d b=%d\n", a, b); // a=20 b=10
17}
Output

Before swap: a=10 b=20
After swap : a=20 b=10
      
📝 Key Takeaways
  • A pointer stores the address of a variable; it 'points to' it.
  • & gives the address; * gives the value at an address.
  • Each concept has its own program: & and *, change via pointer, arrays, swap, NULL.
  • Array name = address of the first element; *(p+i) walks the array.
  • Call by reference uses & and * so a function can change original variables.
  • Swap is the classic call-by-reference example.
  • Always check for NULL before using a pointer.
  • (Advanced pointer topics — pointers to functions, linked lists — are beyond beginner scope.)

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1