Search⌘ K
AI Features

Pass by Value

Explore the concept of pass by value in C functions to understand how arguments are copied to different memory locations. Learn why modifying these copies inside a function does not affect the original variables and see how this impacts operations like swapping values. This lesson helps clarify how function calls handle data and when pass by value is appropriate.

Introduction

Using our knowledge of stack and function call mechanism, let’s introduce the concept of pass by value.

We aim to implement a swap function that we can use throughout the program to swap the values of two variables.

C
#include <stdio.h>
void swap(int a, int b)
{
int aux = a;
a = b;
b = aux;
}
int main()
{
int a = 5, b = 6;
printf("Before swap: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}

Let’s execute the code and look at the output:

Before swap: a = 5, b = 6
After swap: a = 5, b = 6

Bummer! It didn’t work. Both a and b didn’t change, but we can see that we swapped them inside the swap function.

Investigating the code

We should use our newly acquired skill of creating ...