Thuta Learning
C
IntermediateProgrammingBeginner

Function Parameters

CLesson 1925 min

What you'll walk away with

  • Explain why changing a by-value parameter never changes the caller's variable
  • Write a pointer parameter and pass an address with & to modify the caller's variable
  • Recognise that an array parameter is really a pointer and pass the element count as a separate size_t
  • Mark read-only pointer parameters const and decide, check and document whether NULL is allowed

Explain it simply

Explain it simply

A parameter is the door through which data enters a function. When you call greet("Sai", 20), "Sai" and 20 are the arguments, and the name and age variables that receive them inside the function are the parameters. Because nothing is hard-coded, the same function works for anyone you pass in.

C's most important rule is that every argument is photocopied before the function gets it. The function can scribble on its copy as much as it likes, while the caller's original stays untouched. If you want the function to edit the original, you hand over where it lives, its address, instead of a copy.

Problem → Why → Solution

The problem: a swap() that swaps nothing

Say you want a function that exchanges the values of two variables. The code below compiles without a single warning, and a printf inside the function even shows a and b really trading places. Yet back in main(), x is still 3 and y is still 8.

swap_bug.c
#include <stdio.h>

void swap(int a, int b) {     /* a and b are copies */
    int tmp = a;
    a = b;
    b = tmp;                  /* only the copies are swapped */
}

int main(void) {
    int x = 3, y = 8;
    swap(x, y);
    printf("x=%d y=%d\n", x, y);   /* prints x=3 y=8 */
    return 0;
}

Why does nothing change?

Calling swap(x, y) copies the values of x and y into two brand-new variables, a and b. All the work happens on those copies, and they disappear when the function returns. To change x and y themselves, the caller must pass their addresses (&x and &y) and the function must write through the pointers.

Core concept: passing a copy versus passing an address

Every call creates each parameter as a fresh local variable that exists only for that call and starts out holding the argument's value. This is called pass by value, and it is the only way C passes arguments. When a prototype is in scope, each argument is also converted to the parameter's type, so passing 3.9 to an int parameter quietly delivers 3. Since the copy is private, reusing a parameter as a working variable is perfectly safe.

When a function must modify the caller's variable, declare the parameter as a pointer (int *score) and have the caller pass &score. The pointer itself still arrives as a copy, but the copy holds the same address, so writing *score = 0; lands directly in the caller's variable. That is exactly why scanf("%d", &age) needs the &.

Arrays are the special case. An array is never copied; it decays into a pointer to its first element. So int values[] and int *values mean the same thing in a parameter list: the function can modify the caller's elements directly, and it has no way to know how many elements there are. That is why the count travels as a separate size_t parameter.

Writing const int *values for a pointer the function only reads makes the compiler reject an accidental values[0] = 0; inside it. It also tells human readers that they can hand over an array without worrying that it will come back changed. For every pointer parameter, also decide whether NULL is allowed and what happens then, and write it in a comment. A pointer type alone does not say who owns the memory or who must free it, so that belongs in the comment too.

Mental model: copy or address?
  1. Caller evaluates each argument
  2. The value is copied into a new parameter
  3. The function works on its own copy
  4. Only an address (&x) lets *p change x

An array argument arrives as the address of its first element, so send its length alongside it.

General pattern

c
/* by value: the function gets a copy */
ReturnType name(Type param);

/* by address: the function may change *out */
void name(Type *out);

/* read-only array: pointer + element count */
ReturnType name(const Type *items, size_t count);

/* calls */
name(value);   name(&variable);   name(array, count);

Take Type param when a copy of the value is enough. Declare Type *out and pass &variable when the caller's variable must change. For arrays, pass the pointer together with a count, and add const when the function only reads.

Example: copies, pointers and a read-only array

This program puts three kinds of parameter side by side. Compare the output with the code: try_to_reset() edits only its copy, reset() changes the caller's score through a pointer, and total() receives an array as a const pointer plus a count.

parameters.c
#include <stdio.h>

void greet(const char *name, int age) {
    printf("Hello %s, age %d\n", name, age);
}

void try_to_reset(int score) {
    score = 0;                       /* changes the local copy only */
    printf("inside try_to_reset: %d\n", score);
}

void reset(int *score) {
    *score = 0;                      /* writes to the caller's variable */
}

int total(const int values[], size_t count) {
    int sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += values[i];
    }
    return sum;
}

int main(void) {
    greet("Sai", 20);
    greet("Nandar", 22);

    int score = 42;
    try_to_reset(score);
    printf("after try_to_reset: %d\n", score);
    reset(&score);
    printf("after reset: %d\n", score);

    int marks[] = {70, 85, 90};
    size_t count = sizeof marks / sizeof marks[0];
    printf("total of %d marks: %d\n", (int)count, total(marks, count));
    return 0;
}

Code breakdown

  1. greet()void greet(const char *name, int age) {

    Two parameters: name points at a string literal and is const because the function only reads the text, while age is a plain int copy.

  2. Copy onlyscore = 0; /* changes the local copy only */

    The score inside try_to_reset() shares a name with main()'s score but is a separate variable. It becomes 0 here, while main() still sees 42.

  3. Through a pointer*score = 0; /* writes to the caller's variable */

    The * follows the pointer, so this line stores 0 straight into main()'s score.

  4. Read-only arrayint total(const int values[], size_t count) {

    values[] is really a const int * pointer. The function cannot know how many elements exist, so count comes separately, and const forbids changing the elements.

  5. Passing an addressreset(&score);

    & takes the address of score. Forget it and write reset(score), and GCC rejects passing an int where a pointer is expected.

  6. Counting in the callersize_t count = sizeof marks / sizeof marks[0];

    Only in main(), where marks is declared, does sizeof report the whole array's bytes. With 4-byte ints, 12 bytes divided by 4 gives 3 elements.

You should see
Hello Sai, age 20
Hello Nandar, age 22
inside try_to_reset: 0
after try_to_reset: 42
after reset: 0
total of 3 marks: 245

What each parameter form promises the caller

Reading a signature tells you whether a function can change your data. The table collects the forms you will meet most often.

ParameterWhat the function receivesCan it change caller data?
int na copy of the valueNo
int *pthe address of the caller's intYes, through *p
const int *pa read-only view of an addressNo, the compiler blocks writes
int a[] / int *aa pointer to the first elementYes, the elements

Converting each argument to its parameter type can lose data without anyone noticing. The program below compiles cleanly even with -Wall -Wextra; only -Wconversion makes GCC warn "conversion from 'double' to 'int' changes value".

conversion.c
#include <stdio.h>

void show_age(int age) {
    printf("age: %d\n", age);
}

int main(void) {
    show_age(3.9);      /* the double is converted to int: 3 */
    show_age('A');      /* a char is a small integer: 65 */
    return 0;
}

In real projects

Where this shows up in real projects

The standard library itself follows these rules. In size_t strlen(const char *s), const promises the string will not be modified, and scanf writes its results into the addresses you pass. qsort(base, count, size, compare) also receives an array as a pointer paired with an element count.

Embedded firmware and library APIs very often reserve the return value for a success or error code and hand back the real result through an output pointer, as in int read_sensor(int *out_value). Code reviewers ask three questions about every pointer parameter: can it be NULL, how many elements may be read, and who frees the memory? Functions that leave those questions unanswered are where buffer overflows and double frees tend to begin.

Common mistakes

Common mistakes

1. Expecting a by-value change to reach the caller

void add_bonus(int score) { score += 10; } never touches the caller's variable. Either return the new value and write score = add_bonus(score);, or take int *score and call add_bonus(&score). GCC's -Wextra sometimes flags such a parameter as "set but not used", which is a strong hint.

2. Using sizeof on an array parameter

Inside a function, sizeof values / sizeof values[0] divides the size of a pointer, not of the array, so on a 64-bit system it is always 8 / 4 = 2. GCC warns "'sizeof' on array function parameter 'values' will return size of 'const int *'". Compute the count in the caller and pass it in.

3. Passing a value where an address is expected

Writing reset(score) makes GCC 16 stop with "passing argument 1 of 'reset' makes pointer from integer without a cast" and suggest adding &. Older compilers only warned and then used 42 as an address, which crashes at runtime, so treat such warnings as errors.

4. Dereferencing a pointer that may be NULL

If callers are allowed to pass NULL, check it with if (out == NULL) return -1; before writing *out = value;. If NULL is not allowed, state that rule clearly in the comment above the function.

Best practices

Best practices

  • Add const to every pointer parameter the function only reads.
  • Whenever you pass an array, pass its element count as a size_t next to it.
  • Name output parameters with an out_ prefix and document the NULL rule in a comment.
  • Compile with gcc -Wall -Wextra and fix every parameter-related warning.

Mini challenge

Mini challenge: swap() and find_max()

Write two functions that use pointer and read-only array parameters, and test both normal input and edge cases such as NULL and an empty array in main().

  • void swap(int *a, int *b) exchanges two values and does nothing if either pointer is NULL
  • int find_max(const int *values, size_t count, int *out_max) returns 0 on success and -1 for NULL or count == 0
  • Temporarily add values[0] = 0; inside find_max(), read the compiler error, then remove it
  • main() prints the values before and after swap, a swap with NULL, the maximum, and the empty-array case
params_challenge.c
#include <stdio.h>

/* Swaps two ints. Does nothing if either pointer is NULL. */
void swap(int *a, int *b) {
    // TODO: return early on NULL, then exchange *a and *b
}

/* Returns 0 and stores the largest value in *out_max,
   or -1 if values/out_max is NULL or count is 0. */
int find_max(const int *values, size_t count, int *out_max) {
    // TODO: validate the arguments
    // TODO: loop over the elements and keep the largest
    return -1;
}

int main(void) {
    // TODO: swap x = 3 and y = 8 and print before/after
    // TODO: call swap(&x, NULL) and show nothing changed
    // TODO: print the max of {12, -4, 17, 9}, then try count 0
    return 0;
}

Expected: The program prints: before swap: x=3 y=8 after swap: x=8 y=3 swap with NULL changed nothing: x=8 max of 4 values: 17 empty array: no maximum

Show hint

Inside swap(), save *a in int tmp before overwriting it with *b. Work out the array size in main() with sizeof temps / sizeof temps[0] and pass it to find_max().

Show solution
params_challenge.c
#include <stdio.h>

/* Swaps two ints. Does nothing if either pointer is NULL. */
void swap(int *a, int *b) {
    if (a == NULL || b == NULL) {
        return;
    }
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

/* Returns 0 and stores the largest value in *out_max,
   or -1 if values/out_max is NULL or count is 0. */
int find_max(const int *values, size_t count, int *out_max) {
    if (values == NULL || out_max == NULL || count == 0) {
        return -1;
    }
    int best = values[0];
    for (size_t i = 1; i < count; i++) {
        if (values[i] > best) {
            best = values[i];
        }
    }
    *out_max = best;
    return 0;
}

int main(void) {
    int x = 3, y = 8;
    printf("before swap: x=%d y=%d\n", x, y);
    swap(&x, &y);
    printf("after swap:  x=%d y=%d\n", x, y);
    swap(&x, NULL);
    printf("swap with NULL changed nothing: x=%d\n", x);

    int temps[] = {12, -4, 17, 9};
    size_t n = sizeof temps / sizeof temps[0];
    int max;
    if (find_max(temps, n, &max) == 0) {
        printf("max of %d values: %d\n", (int)n, max);
    }
    if (find_max(temps, 0, &max) != 0) {
        printf("empty array: no maximum\n");
    }
    return 0;
}

Quick quiz 1 / 3

Given void bump(int n) { n++; }, what does int x = 5; bump(x); printf("%d", x); print?

Quick quiz 2 / 3

Inside double average(const int values[]), what is wrong with computing the count as sizeof values / sizeof values[0]?

Quick quiz 3 / 3

Which signature promises the caller that the array will only be read?

What to remember

  • C copies every argument into a new parameter, so changing a by-value parameter never affects the caller.
  • To modify the caller's variable, declare a pointer parameter and pass &variable.
  • An array parameter is a pointer to the first element: pass its length as a size_t and never use sizeof on it inside the function.
  • Make read-only pointers const and document the NULL and ownership rules in a comment.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Function Parameters | Thuta Learning