By Value vs. By Reference in C

Image generated by Microsoft Copilot

Hello world, this is our first article. It requires some previous technical knowledge of C, was made for fun and it does not represent future articles which will be more structured and easy to understand 😄.

By default, the C programming language uses the pass "by value" approach when calling a function with some arguments. For instance, please consider the following snippet of C code:

#include <stdio.h>

void f (int x){
  printf("%d\n", x); //prints 0 on the stdout
  x = 1; //manipulation of x
  printf("%d\n", x); //prints 1 on the stdout
}

int main(int argc, char *argv[]) {
  int x = 0; //initial value
  f(x); //x is passed by value
  printf("%d\n", x); //prints 0 on the stdout

  return 0;
}

Call by value (source code)

//output

0
1
0

Call by value (output)

The initial value of x (i.e., 0) is passed to the function f "by value", which means that the function creates a internal copy of the variable x value and all subsequent manipulations (e.g., assigning a new value) within the function are done to that copy.

To change this behaviour, it is possible to pass the variable x "by reference". In this way, by using the reference operator &, the function f receives the memory address of x and can change its initial value.

#include <stdio.h>

void f (int *x){
  printf("%d\n", *x); //prints 0 on the stout
  *x = 1; //manipulation of x
  printf("%d\n", *x); //prints 1 on the stout
}

int main(int argc, char *argv[]) {
  int x = 0; //initial value
  f(&x); //x is passed by reference
  printf("%d\n", x); //prints 1 on the stout

  return 0;
}

Call by reference (source code)

//output

0
1
1

Call by reference (output)

Share this article: