Functions and sizes

Lesson 3 of 14 · C memory foundations

A function groups operations behind an interface. In int twice(int n), int is the result type, n is a parameter, and return n * 2; sends a result to the caller. Arguments are passed by value: the parameter is a separate object. A void return type means no value is returned. A declaration, such as int twice(int n);, tells the compiler the interface before a call; the definition supplies its body.

#include <stdio.h>
int twice(int n) { return n * 2; }
int main(void) {
    int x = 3;
    printf("%d %d\n", twice(x), x);
    printf("char uses %zu C byte\n", sizeof(char));
    return 0;
}

The first line is 6 3: the function did not change x. The second is char uses 1 C byte. sizeof returns a size_t, printed with %zu. A C byte has CHAR_BIT bits, at least eight; it need not be an octet. sizeof(int) and pointer sizes are implementation-dependent. Do not infer the size of every type from whether the system is called 32-bit or 64-bit. %d expects an int; incompatible printf arguments can cause undefined behavior. sizeof measures storage, not the number of meaningful characters in a string.

Calls, return values, and measurement

At a call, argument values initialize the function’s parameter objects. A change to n inside twice does not change x; to modify a caller’s object deliberately, pass its address and use a pointer, as the next chapter shows. A function returning void may perform an effect without returning a value. A prototype should match the definition and be visible at the call site. In twice, multiplication must remain within the range of int; this example uses the safe input 3.

sizeof reports the number of C bytes occupied by a type or object, including struct padding. It does not evaluate an ordinary non-variable-length operand, so sizeof x does not change x. A variable-length array is an important exception. size_t is an unsigned type appropriate for sizes, not necessarily the same type as unsigned int; use %zu when printing it. Type widths, value ranges, alignment and pointer widths vary by implementation. <limits.h> provides integer limits and CHAR_BIT, while <float.h> describes floating-point properties. Measure the actual type, not an assumed machine word.

Chapter index · Course index