C ยท Chapter 26 of 45

C Function Parameters

Parameters let you pass data into a function so it can operate on different values each time it's called. In C, arguments are passed by value by default, meaning the function receives a copy.

To let a function modify the caller's original variable, you must pass a pointer to it, a technique often called 'pass by reference' even though C only truly supports pass by value.

Syntax
void func(int x);       // pass by value
void func(int *x);      // pass by pointer

Pass by value

When you pass a normal variable to a function, C copies its value into the parameter. Changes made inside the function do not affect the original variable.

Pass by pointer

Passing a pointer (an address) lets the function dereference it and modify the original variable directly, since it has access to the actual memory location.

Example 1 (c)
#include <stdio.h>

void addOne(int x) {
  x = x + 1;
}

int main() {
  int a = 5;
  addOne(a);
  printf("%d\n", a);
  return 0;
}
Output
5

Since x is a copy of a, changing x inside addOne does not affect a.

Example 2 (c)
#include <stdio.h>

void addOne(int *x) {
  *x = *x + 1;
}

int main() {
  int a = 5;
  addOne(&a);
  printf("%d\n", a);
  return 0;
}
Output
6

Passing &a lets addOne modify the original variable through the pointer.

Key points

  • C passes arguments by value by default โ€” the function gets a copy.
  • Pass a pointer to allow a function to modify the caller's variable.
  • Arrays are effectively passed by reference since they decay to pointers.
  • Function parameter names don't need to match the caller's variable names.
๐Ÿ’ก Note: If a function needs to change multiple values in the caller, pass pointers to each of them.

๐Ÿ“ Quick Quiz

1. How does C pass arguments by default?

2. How can a function modify a caller's variable directly?

3. Are arrays passed by value or effectively by reference in C?