How to write functions

Define and call a function

State the return type and parameter types. A function definition must be visible or declared before it is called.

int square(int number)
{
    return number * number;
}

int result = square(6);

Use a prototype

A prototype lets the compiler check calls before the full definition appears. Write void for a function with no parameters.

double circle_area(double radius);

int main(void)
{
    printf("%.2f\n", circle_area(2.0));
}

double circle_area(double radius)
{
    return 3.141592653589793 * radius * radius;
}

Return a meaningful status

A non-void function must return a suitable value on every reachable path. For operations that may fail, return a status and place the result in an output parameter.

Keep responsibilities narrow

Prefer functions that do one clear job. Document ownership, valid ranges, buffer sizes, and whether pointer arguments may be null.