Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 135 ยท Functions

Parameters and Return Values

How C passes arguments by value, how return values work, how to return several results with out-parameters or structs, and how arrays behave as parameters.

In Functions you wrote functions that take inputs and hand back a result. This lesson looks closely at how that data actually travels. C has one simple rule: every argument is passed by value. The function receives a copy, and nothing it does to that copy reaches the caller. That rule explains why a naive swap function doesn't work, why functions that need to change your variables take pointers, and why arrays seem to break the rule (they don't, quite).

You'll also see the ways a C function can deliver results: a single return value, a status code plus out-parameters, or a whole struct returned at once. Choosing between them is one of the everyday design decisions in C.

Pass by value

When you call f(x), C evaluates x, then initializes the parameter with that value. The parameter is a separate local variable. Changing it changes only the copy:

C The function gets a copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

count is still 42 after the call, and x and y are not swapped, even though the function swapped its own copies perfectly. Pass by value has a real advantage: a caller can be sure that a call like print_total(price) won't change price behind its back. Any expression can be an argument, too: try_to_reset(count * 2 + 1) is fine, because there is no need for a variable to modify.

Arguments are converted to the parameter type

If an argument's type differs from the parameter's, it's converted as if by assignment, provided the compiler has seen the function's declaration. Passing 7 to a double parameter gives 7.0. Passing 3.9 to an int parameter silently cuts it to 3. GCC only warns about such narrowing with -Wconversion, which isn't part of -Wall -Wextra, so check your types. Type Conversions and Casts has the full rules.

Order of evaluation is unspecified

In f(a(), b()), C doesn't say whether a() or b() runs first. GCC on x86-64 often evaluates right to left, other compilers left to right. That only matters when the arguments have side effects, so don't write calls like printf("%d %d\n", next(), next()) and expect a particular order. Store the results in variables first.

Out-parameters: letting a function change your variables

To let a function modify a caller's variable, pass the variable's address with &, and declare the parameter as a pointer with *. Inside the function, *p means "the variable p points to". The address is still passed by value, but a copy of an address points at the same variable:

C swap that works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Now x is 2, y is 1 and the price is 100.00. You've already used this mechanism: scanf("%d", &n) takes the address of n so it can store the number it reads. Pointers get a full chapter starting at Pointers; Pointers and Functions goes deep on out-parameters. For now, remember the pattern: &variable in the call, type *name in the parameter list, *name in the body.

Returning values

A function returns at most one value, and the caller decides what to do with it: store it, print it, pass it straight into another call, or ignore it. The value is converted to the declared return type, so a function declared int that executes return 2.9; returns 2.

What if you need two or more results, like the minimum and the maximum of an array, or a parsed number and whether parsing succeeded? C offers three common designs.

Design 1: return a status, deliver results through pointers

This is the most common style in C libraries. The return value says whether it worked, and the results go into out-parameters. scanf, strtol and most POSIX functions work this way:

C Status code plus out-parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows min -3 and max 31, then that 07:45 is 465 minutes and 23:59 is 1439, while 25:00 and noon are rejected. Notice that the out-parameters are only written on success, and the caller only reads them on success. That's the contract that makes this style safe. Naming out-parameters with an _out suffix makes their direction obvious in the function header.

Design 2: return a struct

A function can return a whole struct, which bundles several values together. The struct is copied back to the caller just like an int. This is clean and safe for small structs (a few numbers), and modern compilers make it cheap:

C Returning a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The .count = count syntax is a designated initializer, and (int[]){3, 9, 4} is a compound literal, a temporary array written in place. Both arrived in C99, and Structures covers them. Structs can be passed into functions by value too, which copies every member; for large structs, pass a pointer instead (Structures and Pointers).

Design 3: use a special return value

Some functions return a value that can't be a real result to signal failure: -1 for "not found" from a search, EOF from getchar, NULL from malloc or fopen. It's compact, but only works when such a value exists, and callers must remember to check it.

Design Example Good for
Return status, results via pointers bool parse_time(const char *s, int *out) Operations that can fail; several results
Return a struct struct stats compute_stats(...) Several related results, small data
Special value int find(...) returns -1 Simple lookups with an obvious "impossible" value

Arrays as parameters

Arrays look like an exception to pass by value. When you pass an array, the function can change its elements:

C Arrays are not copied

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The array is not copied. When you pass data, C passes the address of its first element, and a parameter written int values[] is really int *values. That's why double_all changes the caller's numbers, and why sizeof values inside the function gives the size of a pointer (8 bytes here) instead of 20. GCC even warns about that sizeof ('sizeof' on array function parameter 'values' will return size of 'const int *'), because it's almost always a mistake; here the warning is the point of the example. This is still pass by value: the pointer is copied. Pointers and Arrays explains the details.

Two consequences:

  • Always pass the length along with an array, as count here. The function has no way to find it.
  • Use const for array parameters the function only reads, like show(const int values[], ...). The compiler then rejects accidental writes, and readers know the array is safe to pass. See const and Pointers.

Parameters as local variables

A parameter is an ordinary local variable that happens to start with the argument's value. You may modify it, which is sometimes handy:

C
int count_digits(unsigned n) {
    int digits = 1;
    while (n >= 10) {
        n /= 10;     /* fine: changes only the local copy */
        digits++;
    }
    return digits;
}

If you want to promise yourself that a parameter won't change, declare it const int n. That const affects only the function's body, not callers, so it's optional in prototypes.

Common mistakes

  • Expecting a function to change a plain argument. It changes a copy; pass a pointer.
  • Passing a value where an address is expected. scanf("%d", n) instead of &n makes scanf write to a random address. GCC warns about format mismatches, so pay attention.
  • Using sizeof on an array parameter to get its length. It gives the pointer size.
  • Writing to out-parameters on failure, or reading them after a failed call. Keep the contract: written only on success.
  • Returning the address of a local variable. The variable dies when the function returns, leaving a dangling pointer. Pointers and Functions covers this trap.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? void bump(int n) { n++; } ... int k = 5; bump(k); printf("%d", k);

    bump receives a copy of k and increments the copy. The caller's k is still 5.
  2. 2. Which call lets void set_zero(int *p) { *p = 0; } reset the caller's variable total?

    The function needs the address of total, which is &total. Inside, *p = 0 writes to the variable at that address.
  3. 3. void fill(int a[], int n) sets every element to 7. After int v[3] = {0}; fill(v, 3); what is v[1]?

    Passing an array passes a pointer to its first element, so fill writes into the caller's array. v[1] becomes 7.
  4. 4. Inside void f(int a[10]), what is sizeof a on a typical 64-bit system?

    An array parameter is really a pointer, int *a, so sizeof gives the pointer size. The 10 in the brackets is ignored.
  5. 5. A function must report the quotient and the remainder of a division, and fail if the divisor is 0. Which design fits best?

    The function has two results and can fail. A status plus out-parameters, or a struct, delivers everything; -1 could be a real quotient.

Summary

  • C passes every argument by value: the parameter is a fresh copy, and changes to it don't affect the caller.
  • Arguments are converted to the parameter types; the order in which arguments are evaluated is unspecified.
  • To let a function modify a caller's variable, pass its address (&x) to a pointer parameter (int *p) and write through *p.
  • A function returns one value. For several results, return a status with out-parameters, return a struct, or use a special "failure" value.
  • Passing an array passes a pointer to its first element: the function can change the elements, sizeof gives the pointer size, and you must pass the length separately. Mark read-only array parameters const.

Next: Declarations, Prototypes and Headers, where you'll learn how to call a function before it's defined and how header files work.