SyntaxStudy
Sign Up
C Pass-by-Value and Pass-by-Pointer
C Beginner 1 min read

Pass-by-Value and Pass-by-Pointer

C is strictly pass-by-value: when you call a function, the arguments are copied into the function's parameter variables. Modifying a parameter inside the function has no effect on the caller's variable. This is safe and predictable, but it means you cannot use a function to change a variable in the calling scope without extra work. To allow a function to modify a caller's variable, you pass the address of that variable using the `&` operator. The function receives a pointer to the variable and dereferences it with `*` to read or write the original. This is sometimes called "pass by reference" in C, though it is really pass-by-value of a pointer. The same technique is used to return multiple values from a function via output parameters. Large structs and arrays should generally be passed by pointer to avoid the overhead of copying them. For arrays, this happens automatically — the array name decays to a pointer to its first element when used in an expression. To prevent a function from modifying data it receives by pointer, add the `const` qualifier to the pointer parameter, making it a read-only view of the caller's data.
Example
#include <stdio.h>

/* Pass-by-value: caller's x is NOT changed */
void increment_val(int x)
{
    x++;
    printf("inside increment_val: x = %d\n", x);
}

/* Pass-by-pointer: caller's variable IS changed */
void increment_ptr(int *x)
{
    (*x)++;
    printf("inside increment_ptr: *x = %d\n", *x);
}

/* Return two values via output parameters */
void min_max(const int *arr, int len, int *out_min, int *out_max)
{
    *out_min = *out_max = arr[0];
    for (int i = 1; i < len; i++) {
        if (arr[i] < *out_min) *out_min = arr[i];
        if (arr[i] > *out_max) *out_max = arr[i];
    }
}

int main(void)
{
    int a = 10;
    increment_val(a);
    printf("after increment_val: a = %d\n", a);  /* still 10 */

    increment_ptr(&a);
    printf("after increment_ptr: a = %d\n", a);  /* now 11  */

    int data[] = {5, 3, 9, 1, 7, 2};
    int mn, mx;
    min_max(data, 6, &mn, &mx);
    printf("min = %d, max = %d\n", mn, mx);       /* 1, 9   */

    return 0;
}