BeginnerLesson 6 of 18
Functions, Scope & Recursion – C
Defining and declaring functions, call by value, static variables and recursion.
A function has a return type, a name, a parameter list and a body. For the compiler to know a function before its definition, you need a prototype (declaration). Prototypes usually live in header files.
#include <stdio.h>
int fakultaet(int n); // prototype
void increment(int x) {
x++;
printf("in increment: %d\n", x);
}
int zaehler(void) {
static int count = 0; // is preserved between calls
return ++count;
}
int main(void) {
int a = 5;
increment(a);
printf("a = %d\n", a); // still 5!
printf("5! = %d\n", fakultaet(5));
zaehler();
zaehler();
printf("zaehler: %d\n", zaehler());
return 0;
}
int fakultaet(int n) {
return n <= 1 ? 1 : n * fakultaet(n - 1);
}C always passes arguments as a copy ("call by value"). The function increment only changes its own copy. To change the caller's values, you pass a pointer (next level).
Variables are only valid within their block. A local variable hides a global one of the same name ("shadowing"); static in front of a local variable gives it a lifetime of the whole program without making it globally visible.
#include <stdio.h>
int global = 100;
int main(void) {
printf("%d\n", global); // 100
int global = 1; // hides the global variable
printf("%d\n", global); // 1
{
int global = 2; // yet another inner block
printf("%d\n", global); // 2
}
printf("%d\n", global); // 1
return 0;
}WarningRecursion always needs a base case, otherwise the stack overflows (stack overflow). With
int, fakultaet(13) also overflows (undefined behavior for signed numbers) – use unsigned long long for large values.TipWrite
int f(void) instead of int f(): in C, () means "any number of unchecked parameters", whereas (void) means "no parameters".