C: Functions – code examples
Contents
Defining and calling functions
Use case: Bundle recurring logic, e.g. calculations or output formats.
#include <stdio.h>
int quadrat(int x) {
return x * x;
}
void begruesse(const char *name, const char *gruss) {
printf("%s, %s!\n", gruss, name);
}
int main(void) {
begruesse("Ada", "Hello");
printf("%d\n", quadrat(7));
return 0;
}Return type, name, parameters. C has no default values for parameters – if needed, you provide them via your own constants or a struct with options. void means: no return value.
Dispatch table with function pointers
Functions#function pointer#callback#typedef
Use case: Map commands or states to functions without long if chains (menus, interpreters, state machines).
#include <stdio.h>
typedef int (*BinOp)(int, int);
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
struct Befehl { const char *name; BinOp fn; };
int main(void) {
struct Befehl tab[] = {{"add", add}, {"mul", mul}};
for (int i = 0; i < 2; i++) {
printf("%s(6, 7) = %d\n", tab[i].name, tab[i].fn(6, 7));
}
return 0;
}A typedef makes the function pointer type readable. The table maps names to functions; a new command = one more entry.
static variable as a counter
Functions#static#counter#lifetime
Use case: Keep state across multiple calls, e.g. running IDs or call counters.
#include <stdio.h>
int naechste_id(void) {
static int id = 0; // is initialized only once
return ++id;
}
int main(void) {
printf("%d %d %d\n", naechste_id(), naechste_id(), naechste_id());
return 0;
}A static local variable lives as long as the program but is only visible inside the function. Not thread-safe!