Pass by Value
Learn the internals and working of pass by value.
We'll cover the following...
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.
Press + to interact
#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 ...