YOUR C LEARNING COMPANION

Find your next idea.

Learning path
C foundationsChapter 13 of 73

Functions: inputs, results, and contracts

Understand declarations, calls, parameters, return values, scope, and pass-by-value without assuming that a function prints its result.

11 min readFoundationsC17 baseline
Offline reading
In this chapter11 sections

A function gives a piece of work a name. A caller can supply inputs and use its result. We will separate declaring a function, defining its work, and calling it, then explain what information passes between caller and function.

Need the ideas side by side? Open the concept guide.

1. A function has an interface

C17 · translation-unit fragment
int add(int left, int right);

This declaration describes a function named add. It accepts two int arguments and returns an int. The parameter-type information makes it a prototype. There is no body here. Parameter names can explain the jobs, while matching types and compatibility rules govern the interface.

A definition supplies the function body. A call asks it to run. Declaring, defining, and calling are separate actions. A call site may see a declaration while the matching definition is supplied elsewhere in the program.

Complete C17 program
#include <stdio.h>

int add(int left, int right) {
    return left + right;
}

int main(void) {
    int answer = add(2, 4);
    printf("%d\n", answer);
    return 0;
}

This complete C17 example uses small arguments whose sum is representable. add(2, 4) calls the function; its returned value initializes answer. The later printf call requests output. If output succeeds, it writes six and a newline. Defining add does not itself call it, and returning six from it does not itself print six.

2. Arguments supply values to parameters

The values supplied in a call are its arguments. The function receives them through parameters. In add(2, 4), the arguments are two and four. The definition names its parameters left and right. Argument values undergo the conversions required by those parameter types.

C passes arguments by value. For each call, a parameter receives a value of its own. Changing an integer parameter does not change the caller’s integer object. A copied pointer can still refer to shared storage; that is why a function can affect a target through a pointer while arguments are still passed by value.

Complete C17 program
#include <stdio.h>

int next_value(int value) {
    value += 1;
    return value;
}

int main(void) {
    int original = 4;
    int next = next_value(original);
    printf("%d %d\n", original, next);
    return 0;
}

The local parameter changes to five, but the caller’s original remains four. The returned value is how this function deliberately communicates the computed next value. Passing an expression such as original + 2 would also be valid within range; an argument need not be a named variable.

3. A return value is a result, not a display command

return expression; gives control back to the caller and supplies the function’s result, converted to its return type. The caller chooses how to use that result. A void function returns no value and can use return;. Returning a value does not itself print it.

Design all paths deliberately. In C, reaching the end of an ordinary non-void function is not generally a safe way to supply a result; using the missing result can have undefined behavior. Hosted main has a special rule: reaching its closing brace is equivalent to returning zero in C99 and later. Do not generalize that exception to every function.

4. Specify what the function requires and promises

A contract states what inputs a function accepts and what it promises. It can also describe changes and failures. Our add example requires its sum to fit in int. The prototype gives type information, but it does not automatically check every range requirement.

Choose a name and a task that fit together. A calculation function that returns a value can often be understood and checked independently of presentation. A function that also prints, changes global state, and reads input has a larger contract. That can be appropriate, but those effects should be deliberate rather than surprises hidden behind a harmless-looking name.

5. Each invocation has its own ordinary local state

Parameters and ordinary automatic local objects belong to an invocation. Their names have scope in the function’s source, while their objects have runtime lifetimes. Calling the same function again does not mean an ordinary automatic local automatically remembers the previous call’s stored value. Static-storage objects have different lifetime rules.

In recursion, a function calls itself directly or through other functions. Each call has its own ordinary local state. A terminating design needs a stopping case and progress toward it. The recursion chapter traces these calls one at a time and explains the resource limits.

6. Write interfaces that say what they mean

In C17, int read_count(void); declares a function with no parameters. int read_count(); does not provide that prototype information; its parameter list is unspecified in that declaration. C23 changes the empty-list meaning so that it also specifies no parameters. Explicit void is clear in both versions.

Use compatible declarations at call sites, commonly through headers in a multi-file program. Library calls also have contracts. With printf, a format must match the types actually supplied after the relevant promotions. A format string does not safely convert any arbitrary argument merely because it contains the display pattern you want.

Go deeper: static and inline are not magic speed switches

For a file-scope function, static gives its identifier internal linkage. Another translation unit cannot link to that name as an external function name, but code there can call the function through a pointer supplied to it. inline does not force machine-code substitution and also has function-definition and linkage rules; a header full of plain inline definitions is not automatically a correct multi-file design.

Think it through

A function changes its integer parameter from four to five and returns five. If the caller ignores the returned result, has its original integer object necessarily changed?

Read the explanation

No. The parameter received a copy of the value. The caller must deliberately use the returned result, or the function must have another valid, specified way to affect a shared object. Returning and modifying the caller’s original object are different actions.

Primary references and further reading

After recursion, revisit the later callback and variadic-function chapters once pointers and library interfaces feel familiar.

Optional visual model: Follow a function argument

Follow a function argument

VISUAL MODEL

Watch a parameter receive a value, then change without changing the caller’s object.

replace is a separate function. The final two lines belong inside another function that calls it.

  1. void replace(int x) {
  2. x = 9;
  3. }
  4. /* inside a different function: */
  5. int caller = 4;
  6. replace(caller);
intcaller4Caller’s object
intx—No active parameter

caller is initialized to 4 in the calling function. No replace call is active yet.

C passes argument values. A pointer argument is copied too; that copied pointer can still refer to an object shared with the caller. This model passes an int.

Read the complete trace
  1. caller is initialized to 4 in the calling function. No replace call is active yet.
  2. The argument expression caller supplies its current value, 4.
  3. The parameter x is a separate int object initialized from the argument value 4.
  4. x receives 9. caller still holds 4 because it is a different object.
  5. replace returns. The parameter’s lifetime ends, and caller still holds 4.

A call passes values into a separate execution

Compare, follow, and explain this idea

For a function with a suitable prototype, argument values are converted to the parameter types. Each parameter is a separate object for that call. A copied pointer value can still designate an object in the caller.

When this helps Use this model to understand output parameters, independent recursive calls, and the difference between changing a parameter and changing its target.

Read the ideas side by side

Argument
The expression supplied at the call, such as score or &score.
Parameter
The named object used by that call’s function body, such as value or target.

A parameter is not a second name automatically bound to the caller’s variable.

Change a copied int
value = 9 changes the parameter object value.
Write through a copied pointer
*target = 9 changes the live int object designated by the copied pointer.

C still passes a value in both calls.

Function declaration
Introduces the function and, with a prototype, describes its parameter types.
Function definition
Also supplies the body executed when that function is called.

A body must be provided where required; a declaration alone does not supply the implementation.

Follow the reasoning

The pointer call below receives &score, so its target is a valid live int. The function is not a general validator for arbitrary pointers.

C17 · illustrative fragments in the stated context

  1. void change_copy(int value) { value = 9; (void)value; }
  2. void change_target(int *target) { *target = 9; }
  3. /* inside a caller: */
  4. int score = 4;
  5. change_copy(score);
  6. change_target(&score);
  1. Initialize the caller’s object

    score is an int object holding 4.

  2. Call change_copy

    The value 4 is passed to its int parameter. Assigning 9 to that separate parameter does not assign to score.

  3. Return from the first call

    The parameter’s lifetime ends. score still holds 4.

  4. Call change_target

    &score supplies a pointer value. The parameter target receives that value and designates score.

  5. Write through target

    *target = 9 changes score. Returning ends the pointer parameter’s lifetime, not the caller’s score object.

Common misconceptions

These statements are misleading. Open each one to see why.

MisconceptionPassing a pointer switches C into pass-by-reference.

The pointer value is passed by value. It permits indirect access to a suitable target, while the parameter remains a separate pointer object.

MisconceptionA recursive call overwrites the previous call’s parameters.

Each active call has its own automatic parameter objects. A shared static object, if used, is a separate issue.

MisconceptionFunction arguments are always evaluated left to right.

C does not generally specify their evaluation order. Avoid depending on an order, especially when arguments read and modify the same object.

Go a little deeperOptional technical detail

Array parameter spelling does not copy an array

A parameter declared as an array is adjusted to a pointer parameter. Pass the needed count separately or use an interface with a clearly documented size contract.

Macros do something different

A function-like macro substitutes preprocessing tokens. It does not create parameter objects or a function call boundary. Parentheses can fix grouping while leaving repeated evaluation possible.

C17 In C17, a declaration such as int f(); does not provide a parameter-type prototype. int f(void); explicitly declares no parameters. The guide’s calls use prototypes.

C23 In C23, an empty parameter list in int f(); specifies no parameters and provides a prototype. This change does not make function arguments evaluate left to right.

Check the source rules

Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.

Say it in your own words

If target is a copy, how can *target change score?

Compare with an explanation

The copied pointer value still designates score. Changing target itself and writing through *target are different operations.

Before you move on

  • A declaration, definition, and call describe different parts of using a function.
  • C passes argument values to parameters; copied pointers can still access shared targets.
  • A function’s useful contract includes ranges, effects, and failure behavior beyond its type signature.
Keep these ideas separate
Returning / Printing
A return gives a result to a caller; output requires a separate effect such as a suitable library call.
Explain it in your own words

How can a function change a caller’s object through a pointer while argument passing remains by value?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

Does passing a pointer argument change C into pass-by-reference?
Read the explanation for every choice
  1. No. The pointer value is copied, and the copy can refer to a shared object.

    ✓ Correct reasoning. The function may modify a permitted pointed-to object, while its parameter is still a separate pointer object.

  2. Yes, pointer parameters are aliases for the caller’s pointer variable.

    A pointer parameter receives a value; assigning that parameter does not directly assign the caller’s pointer object.

  3. A pointer argument copies the whole pointed-to allocation.

    Copying a pointer value does not copy the objects it refers to.

C17

Quick reference from the earlier edition

This compact reference keeps existing links and saved passages available. Read the expanded lesson above for the full context.

Declaration, Definition, and Prototypes

A declaration announces a function; a definition also supplies its body. In C17, a prototype gives parameter types so calls can be checked: int add(int, int);. A declaration int f(); is not a prototype and leaves the parameter list unspecified; int f(void); specifies no parameters. In C23, f() specifies no parameters too. Use headers to share the same compatible prototype across source files.

Parameter Passing

C passes arguments by value. A pointer argument is a copied pointer value; dereferencing it can change the caller's pointed-to object, but assigning a different address to the local parameter does not change the caller's pointer. Array expressions used as arguments normally convert to a pointer to the first element, and array parameters are adjusted to pointer parameters. This is not an exception to pass-by-value: the pointer value is copied.

Recursion

A recursive function calls itself directly or indirectly. A terminating computation needs a stopping condition and progress toward it. Typical implementations retain call state on a stack, so deep recursion can exhaust resources; the C standard does not mandate a physical stack or a fixed amount of stack space per call, and optimizations may remove some calls. Iteration is often preferable for large input depths.

Variadic Functions

Functions like printf accept a variable number of arguments using the <stdarg.h> facilities: va_list holds the argument-traversal state, va_start initializes it, va_arg retrieves each argument by its expected type, and va_end cleans up. Because there is no runtime record of how many arguments were passed or what type each one is, the function must infer this from context — typically a format string — which is also why mismatched printf format specifiers are a classic source of undefined behavior.

Function Pointers

A function pointer stores the address of a function, allowing functions to be passed as arguments, stored in arrays as dispatch tables, or returned from other functions:

C17 · illustrative fragment
int add(int a, int b) { return a + b; }

int function_pointer_example(void) {
    int (*op)(int, int) = add;
    return op(3, 4);  /* returns 7 */
}

Static and Inline Functions

A file-scope static function has internal linkage: its identifier is not available for external name linkage from another translation unit. The function can still be called through a pointer supplied to code elsewhere. inline does not force call expansion and also has definition and linkage rules that matter in multi-file programs; it is not simply a speed switch.

The main Function

In a hosted C environment, startup calls main. Portable forms are int main(void) and int main(int argc, char *argv[]), or equivalent declarations; implementations may support additional forms. In a freestanding environment, startup is implementation-defined and need not use main. Returning 0 or EXIT_SUCCESS reports successful termination; EXIT_FAILURE reports unsuccessful termination. The meanings of other exit values are implementation-defined. Since C99, reaching the closing brace of main is equivalent to returning 0.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 13 / 73

In this chapter

Functions: inputs, results, and contracts

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping