Functions
Declaring and defining functions, passing by value, and returning results through pointers.
Runs in Zerethon IDE · C (GCC 14)
Official C documentation ↗
main.c
#include <stdio.h>
int square(int x); /* declaration (prototype) */
void min_max(const int *values, int n, int *min, int *max);
int main(void) {
int values[] = {4, 8, 6};
int lo, hi;
min_max(values, 3, &lo, &hi);
printf("%d %d %d\n", square(9), lo, hi);
return 0;
}
int square(int x) { /* definition */
return x * x;
}
void min_max(const int *values, int n, int *min, int *max) {
*min = *max = values[0];
for (int i = 1; i < n; i++) {
if (values[i] < *min) *min = values[i];
if (values[i] > *max) *max = values[i];
}
}
Output
81 4 8
- A function must be declared before it is called: define it above
main, or write its prototype first. - Arguments are copied. To let a function change a variable, pass its address (
&lo) and write through the pointer (*min = …). - An array passed to a function becomes a pointer — pass its length too.