Review the key points with a cheat sheet, six code-reading questions, and a checklist of common mistakes.
// Return type, function name(parameter type and name, ...) int square(int x) { return x * x; } int main(void) { printf("%d\n", square(5)); // 25 }
voidreturn returns a value (and can exit early) void add10(int x) { x += 10; // x is a copy } int main(void) { int a = 5; add10(a); printf("%d\n", a); // Still 5! }
int g = 100; // Global void f(void) { int x = 1; // Local to f } int main(void) { int x = 2; // main's x (a separate variable) f(); printf("%d %d\n", x, g); // 2 100 }
void fill(int a[], int n) { for (int i = 0; i < n; i++) a[i] = 7; } int main(void) { int a[3] = {0}; fill(a, 3); // a becomes {7, 7, 7} }
sizeof cannot determine its length; pass the length separately int factorial(int n) { if (n <= 1) return 1; // Base case! return n * factorial(n - 1); } // factorial(4) = 4*3*2*1 = 24
// Declare first; define the body later int add(int, int); int main(void) { printf("%d\n", add(2, 3)); } int add(int a, int b) { return a + b; }
int square(int x) { return x * x; } int main(void) { printf("%d\n", square(3) + square(4)); }
25. These are also the squared sides of a 3–4–5 right triangle.void add10(int x) { x += 10; } int main(void) { int a = 5; add10(a); printf("%d\n", a); }
5. To update a, pass its address or assign a returned result, for example a = add10(a).void setZero(int a[], int n) { for (int i = 0; i < n; i++) a[i] = 0; } int main(void) { int a[3] = {7, 8, 9}; setZero(a, 3); printf("%d %d %d\n", a[0], a[1], a[2]); }
0 0 0. The pointer itself is still passed by value.int g = 100; void f(void) { int g = 1; // Local with the same name printf("f: %d\n", g); } int main(void) { f(); printf("main: %d\n", g); }
f: 1; main prints main: 100. The two variables are separate.int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } printf("%d\n", fact(4));
24. The base case n<=1 returns 1 and stops recursion.void show(int a[]) { printf("%zu\n", sizeof a); } int main(void) { int a[5] = {0}; show(a); }
sizeof a return? int a[] is adjusted to int *a. Thus sizeof a is the pointer size (often 8 bytes), not the array size. Pass the element count separately, for example void show(int a[], int n).returndid not match int causes a returned double to be converted to int. void combined with return x; is invalid. sizeof.