Previous: Inside the Kernel Reading map Next: C++ Programming
Volume III: Paradigms (Chapter 9)Code & tests Chapter diagrams Download editable SVGs
Programming paradigms shape how a problem is understood, from changing machine state to composing functions or exchanging object messages. Recursion, callbacks, and explicit states show how several models can coexist within one program.
Chapter Map
Abstraction shifts attention from machine operations toward the problem being solved. Learning alternative models, including functional and object-oriented approaches, broadens the solutions a programmer can recognize without removing practical performance constraints.
first two volumes approached programming from the machine upward
"high level" historically meant above assembly
Pascal also exposes the stored-program machine model
low-level programming uses knowledge of the machine deliberately
systems software often needs machine-level knowledge
application development has additional tradeoffs
abstraction can shift attention from machine mechanics to the problem
volume examines paradigms beyond familiar imperative programming
several paradigms have already appeared in systems work
language features can influence how a programmer frames a problem
learning several models develops flexibility
A paradigm can concern an entire program or a small technique, so lists of styles do not establish a precise definition. Event loops, text interfaces, shared data, and recursion illustrate the term's varied scope.
previously introduced styles include imperative, functional, declarative, and object-oriented programming
Unix design supplies further examples
preferring text is a representation paradigm
an event-driven program has a repeating event loop
parallel execution and shared-data programming are distinct ideas
recursion is another paradigm, at a different scale
authors disagree on what belongs in the category
ask why the term is needed and what recognizing it helps us do
A paradigm is an approach to understanding the same subject, illustrated through geometry and skiing. Programming differs from an exclusive scientific paradigm shift: several models can coexist, and experience helps choose among them.
Greek origin suggests example/model
social and political discussion also uses "paradigm shift"
common theme: different ways of interpreting one phenomenon
working meaning used by this book:
geometry can be understood visually or through formal statements
individual mental pictures differ even within the visual approach
learning a difficult subject involves forming a usable mental model
skiing is offered as an example outside mathematics and programming
author contrasts the movement and attention of novices and practiced skiers
example's practical problem: retain control of speed while descending
turns can be viewed as the whole trajectory or as means toward a destination
explaining the purpose of an action helps change the model behind it
Floyd applied the paradigm idea to programming
there is no universal recipe for choosing the best paradigm for every task
Imperative programs change state; functional programs compose computations; logic programs search for satisfying relations; object-oriented designs organize behavior behind object interfaces. These broad styles overlap, while ADTs emphasize hidden representations and controlled value operations.
The same styles side by side. A C program written functionally:
make_output describes the whole output as a list, built by
nested calls without assigning anything; only main performs
actions:
struct str_item *make_output(int i, int argc, char **argv)
{
return i >= argc ? NULL :
mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct str_item {
char *str;
struct str_item *next;
};
struct str_item *mkitem(const char *s, struct str_item *tail)
{
struct str_item *p = malloc(sizeof(*p));
p->str = malloc(strlen(s) + 1);
strcpy(p->str, s);
p->next = tail;
return p;
}
struct str_item *make_output(int i, int argc, char **argv)
{
return i >= argc ? NULL :
mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}
struct str_item *main_func(int argc, char **argv)
{
return make_output(0, argc, argv);
}
int main(int argc, char **argv)
{
struct str_item *p, *tmp;
p = main_func(argc, argv);
for (; p; p = tmp) {
tmp = p->next;
fputs(p->str, stdout);
free(p->str);
free(p);
}
return 0;
}
$ ./functional one two
./functional
one
two
Logic programming states facts and rules and lets the system search:
parent(mary, ann).
parent(mary, john).
parent(george, john).
male(george).
male(john).
female(mary).
female(ann).
father(X, Y) :-
parent(X, Y),
male(X).
mother(X, Y) :-
parent(X, Y),
female(X).
brother(X, Y) :-
parent(T, X),
parent(T, Y),
male(X).
?- brother(X, ann).
?- father(F, john).
?- brother(john, john).
The first query finds X = john, the second
F = george. The third also succeeds: nothing in the rule
says that X and Y are different people, so it needs an extra condition
X \= Y.
Haskell, a purely functional language, describes the whole output as
a function of the whole input; interact connects that
function to the streams:
main :: IO ()
main = interact numberLines
numberLines :: String -> String
numberLines input =
unlines $
zipWith addNumber [1..] (lines input)
addNumber :: Integer -> String -> String
addNumber n line =
show n ++ ": " ++ line
$ printf 'first\nsecond\n' | ./number
1: first
2: second
imperative program acts within an execution environment
imperative reasoning centers on state that changes over time
program instructions tell an executor which actions to perform
assignment is a characteristic imperative action
assignment requires a mental model of changing variable values
tracing loops also requires imagining execution over time
book calls this mutable-memory model von Neumann programming
historical von Neumann programming differed in implementation details
procedural and imperative are not identical
historical line-numbered BASIC combined editing and execution
BASIC line numbers also served as jump destinations
GOSUB / RETURN supplied limited call-like control flow
procedural programming decomposes a problem into isolated subprograms
parameters and local state support that separation
assembly programmers can impose procedural organization manually
procedural programming is an important form of imperative organization
command scripting is another imperative style
pure functional programming avoids destructive state updates
functional variables can denote immutable bindings
functions are the main composition units
function syntax alone does not make a program functional
a functional subset can be imposed on an imperative language
without updates, mutable global variables and ordinary state-changing loops disappear
recursive repetition has a resource cost unless tail calls can reuse frames
computability models abstract away finite memory limits
I/O changes the program's observable environment
languages combine pure computations with effects in different ways
Haskell's IO organizes effectful actions as values composed by pure code
monad terminology can be a teaching obstacle
seminar anecdote: several accounts of monads emphasized different intuitions
book does not develop Haskell or monad programming further
restricted C example takes its inputs through command-line arguments
one option allows I/O while keeping other computations free of effects
illustration separates a functional core from effectful wrappers
input/output histories can be encoded as data transformations
interactive input may not exist until after the program produces output
logic programming describes facts and inference rules
Prolog is the main logic-programming example
logic programming requires an inference/search mechanism
family example uses parent, male, and female facts
more facts and rules express richer relational queries
declarative view specifies properties of a desired result
declarative programming is broader than logic programming
relations connect logic predicates with database tables
logic languages can serve as database-query tools
Prolog also includes mechanisms that complicate a purely logical reading
some Prolog programs require reasoning about the solver's search order
object-oriented programming is often explained using three terms
modularity helps control the complexity perceived by a programmer
encapsulation hides implementation behind an interface
object model groups behavior behind individual object interfaces
object-level encapsulation can reduce visible complexity within a module
class describes a family of objects
several classes may support a common interface
polymorphism means that similar syntax can have type-dependent behavior
operator overloading and subtype polymorphism are distinct facilities
abstract data type: representation hidden behind permitted operations
ADTs and object-oriented interfaces both hide implementation
book contrasts value copying with independent object identity
object-oriented and imperative features often coexist in one language
many object-oriented languages still use assignment and changing state
major style labels do not determine every aspect of a program
smaller paradigms can coexist inside a broader one
PROGRAMS = functional
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
parent(mary, ann).
parent(mary, john).
parent(george, john).
male(george).
male(john).
female(mary).
female(ann).
father(X, Y) :-
parent(X, Y),
male(X).
mother(X, Y) :-
parent(X, Y),
female(X).
brother(X, Y) :-
parent(T, X),
parent(T, Y),
male(X).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct str_item {
char *str;
struct str_item *next;
};
struct str_item *mkitem(const char *s, struct str_item *tail)
{
struct str_item *p = malloc(sizeof(*p));
p->str = malloc(strlen(s) + 1);
strcpy(p->str, s);
p->next = tail;
return p;
}
struct str_item *make_output(int i, int argc, char **argv)
{
return i >= argc ? NULL :
mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}
struct str_item *main_func(int argc, char **argv)
{
return make_output(0, argc, argv);
}
int main(int argc, char **argv)
{
struct str_item *p, *tmp;
p = main_func(argc, argv);
for (; p; p = tmp) {
tmp = p->next;
fputs(p->str, stdout);
free(p->str);
free(p);
}
return 0;
}
#include <stdio.h>
const char *strchar1(const char *s, char c)
{
const char *p;
for (p = s; *p; p++)
if (*p == c)
return p;
return NULL;
}
const char *strchar2(const char *s, char c)
{
if (!*s)
return NULL;
if (*s == c)
return s;
return strchar2(s + 1, c);
}
const char *strchar3(const char *s, char c)
{
return !*s ? NULL : *s == c ? s : strchar3(s + 1, c);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <str> <char>\n", argv[0]);
return 1;
}
const char *res = strchar3(argv[1], argv[2][0]);
printf("%s\n", res);
return 0;
}
Recursion is both a calling technique and a way to understand a problem through smaller instances. Language support affects its convenience, but writing a self-call does not itself establish recursive thinking.
languages differ in how naturally they support recursive solutions
study recursion as a model of thought, not only a self-calling technique
Recursive inorder traversal leaves unfinished work in call frames, while an iterative version records nodes and continuation stages in an explicit stack. Both preserve equivalent information; the main difference is how the programmer describes that work.
recursive inorder traversal:
iterative traversal explicitly remembers the path back to ancestor nodes
three states for a saved node:
left subtree completed -> print current value
completed node -> pop its traversal frame
switch fallthrough skips redundant loop iterations for absent children
explicit path list is a stack
recursive calls preserve equivalent information implicitly
both versions save a node and unfinished work for each active subtree
representation of the explicit stack affects cost
main contrast is the programmer's description of the work
%include "calls.inc"
%assign stack_len 1024
%assign num_len 12 ; sign + 10 decimal digits + space
%assign start 0
%assign left_visited 1
%assign completed 2
%assign node_val 0
%assign node_left 4
%assign node_right 8
%assign node_size 12
%assign stack_p 0
%assign stack_st 4
%assign stack_size 8
; Inline traversal records on the hardware stack.
; Use stable operands, not ESP-relative operands.
%macro stack_push 3 ; (size_operand, node_pointer, state)
inc dword %1
push dword %3
push dword %2
%endmacro
%macro stack_pop 1 ; (size_operand)
dec dword %1
add esp, stack_size
%endmacro
global _start
extern sint2str
section .data
new_line db 10
section .text
print_int:
; (val: 8)
; sint2str -> append a space -> write to stdout.
pbegin num_len, ebx, esi, edi
lea edi, [ebp-num_len] ; local conversion buffer
pcall sint2str, [ebp+8], edi
mov byte [edi+eax], ' '
inc eax
mov esi, eax ; length including the space
.write:
scall 4, 1, edi, esi
cmp eax, -4 ; -EINTR: retry
je .write
test eax, eax
jle .error
add edi, eax
sub esi, eax
jne .write ; finish any partial write
pend ebx, esi, edi
.error:
scall 1, 3
tree_push:
; (p: 8, nodes: 12, nodes_used: 16, val: 20)
pbegin 0
mov eax, [ebp+16]
mov edx, [eax]
imul edx, node_size
add edx, [ebp+12] ; tmp = &nodes[*nodes_used]
inc dword [eax] ; (*nodes_used)++
mov ecx, [ebp+20]
mov [edx+node_val], ecx
mov dword [edx+node_left], 0
mov dword [edx+node_right], 0
mov eax, [ebp+8]
mov [eax], edx ; *p = tmp
pend
tree_insert:
; (p: 8, nodes: 12, nodes_used: 16, val: 20)
pbegin 0
mov eax, [ebp+8]
mov eax, [eax]
test eax, eax
je .new_node
mov edx, [ebp+20]
cmp edx, [eax+node_val]
jl .left
jg .right
jmp .end
.new_node:
pcall tree_push, [ebp+8], [ebp+12], [ebp+16], [ebp+20]
jmp .end
.left:
lea eax, [eax+node_left]
pcall tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
jmp .end
.right:
lea eax, [eax+node_right]
pcall tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
.end:
pend
tree_print1:
; (p: 8)
pbegin 0, ebx
mov ebx, [ebp+8]
test ebx, ebx
jz .end
pcall tree_print1, [ebx+node_left]
pcall print_int, [ebx+node_val]
pcall tree_print1, [ebx+node_right]
.end:
pend ebx
tree_print:
; (p: 8)
; [ebp-4] = size
; ebx = s, pointing to the current traversal record
pbegin 4, ebx
mov dword [ebp-4], 0
mov eax, [ebp+8]
test eax, eax
je .end
stack_push [ebp-4], eax, start
.lp:
cmp dword [ebp-4], 0
je .end
mov ebx, esp
mov eax, [ebx+stack_st]
cmp eax, start
je .start
cmp eax, left_visited
je .left_visited
cmp eax, completed
je .completed
jmp .lp
.start:
mov dword [ebx+stack_st], left_visited
mov eax, [ebx+stack_p]
mov eax, [eax+node_left]
test eax, eax
je .lp
stack_push [ebp-4], eax, start
jmp .lp
.left_visited:
mov eax, [ebx+stack_p]
pcall print_int, [eax+node_val]
mov dword [ebx+stack_st], completed
mov eax, [ebx+stack_p]
mov eax, [eax+node_right]
test eax, eax
je .lp
stack_push [ebp-4], eax, start
jmp .lp
.completed:
stack_pop [ebp-4]
jmp .lp
.end:
pend ebx
_start:
; [ebp-4] = p, [ebp-8] = nodes_used
; [ebp-(8+stack_len*node_size)] = nodes[0]
pbegin 8+stack_len*node_size, ebx, esi, edi
mov dword [ebp-4], 0
mov dword [ebp-8], 0
lea ebx, [ebp-4]
lea esi, [ebp-(8+stack_len*node_size)]
lea edi, [ebp-8]
pcall tree_insert, ebx, esi, edi, 1
pcall tree_insert, ebx, esi, edi, 3
pcall tree_insert, ebx, esi, edi, 2
pcall tree_print, [ebp-4]
scall 4, 1, new_line, 1
scall 1, 0
#include <stdio.h>
#include <stdlib.h>
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
struct stack *next;
};
void stack_push(struct stack **s, const struct node *p, const enum state st)
{
struct stack *tmp = malloc(sizeof(*tmp));
tmp->p = p;
tmp->st = st;
tmp->next = *s;
*s = tmp;
}
void stack_pop(struct stack **s)
{
struct stack *tmp = *s;
*s = (*s)->next;
free(tmp);
}
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack *s;
s = NULL;
stack_push(&s, p, start);
while (s)
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(&s, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(&s, s->p->right, start);
break;
case completed:
stack_pop(&s);
}
}
int main()
{
struct node *p;
p = NULL;
tree_insert(&p, 1);
tree_insert(&p, 3);
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_print(p);
printf("\n");
return 0;
}
#include <stdio.h>
enum { stack_len = 1024 };
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
};
void stack_push(struct stack *s, int *size,
const struct node *p, const enum state st)
{
struct stack *tmp = &s[*size];
(*size)++;
tmp->p = p;
tmp->st = st;
}
void stack_pop(int *size)
{
(*size)--;
}
void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
struct node *tmp = &nodes[*nodes_used];
(*nodes_used)++;
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
if (!*p)
tree_push(p, nodes, nodes_used, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, nodes, nodes_used, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, nodes, nodes_used, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack backpath[stack_len], *s;
int size = 0;
stack_push(backpath, &size, p, start);
while (size) {
s = &backpath[size - 1];
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(backpath, &size, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(backpath, &size, s->p->right, start);
break;
case completed:
stack_pop(&size);
}
}
}
int main()
{
struct node *p, nodes[stack_len];
int nodes_used = 0;
p = NULL;
tree_insert(&p, nodes, &nodes_used, 1);
tree_insert(&p, nodes, &nodes_used, 3);
tree_insert(&p, nodes, &nodes_used, 2);
tree_print(p);
printf("\n");
return 0;
}
PROGRAMS = 09-02-01-tree-01
ASSEMBLY = 09-02-01-tree-00
ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)
CC = gcc
CFLAGS = -g -Wall
NASM = nasm
NASMFLAGS = -f elf32 -g
LD = ld
ASLDFLAGS = -m elf_i386
all: $(PROGRAMS) $(ASSEMBLY)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
$(ASSEMBLY): %: %.o $(AOBJMODULES)
$(LD) $(ASLDFLAGS) $^ -o $@
clean:
$(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
%macro pcall 1-*
; call subroutines < (name, param1, param2, param3)
%rep %0 - 1
%rotate -1
push dword %1
%endrep
%rotate -1
call %1
add esp, (%0 - 1)*4
%endmacro
%macro scall 1-4
; system call
; < (interrupt number, param1, param2, param3)
%if %0 > 1
push ebx ; it can only spoil eax, ecx, edx
%endif
%rep %0
%rotate -1
push dword %1 ; push in reverse order
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%endif
%endif
%endif
int 80h
cmp eax, 0xfffff000
jb %%ok
mov ecx, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
%macro pbegin 1-4
; procedure header < (sub, reg1, reg2, reg3)
push ebp
mov ebp, esp
sub esp, %1
%rep %0-1
%rotate 1
push %1
%endrep
%endmacro
%macro pend 0-3
; procedure tail < (reg1, reg2, reg3)
%rep %0
%rotate -1
pop %1
%endrep
mov esp, ebp
pop ebp
ret
%endmacro
global sint2str
section .text
sint2str: ; (number: 8, result: 12) -> string length in eax
push ebp
mov ebp, esp
sub esp, 4
push ebx
push esi
push edi
mov esi, [ebp+8] ; number to convert
mov edi, [ebp+12] ; result buffer
mov ebx, 10
mov dword [ebp-4], 0 ; negative?
cmp esi, 0
jge .not_negative ; signed comparison
not esi
inc esi ; unsigned magnitude
mov dword [ebp-4], 1
.not_negative:
mov eax, esi
xor ecx, ecx
.lp:
xor edx, edx
div ebx
add edx, '0'
mov [edi+ecx], dl
inc ecx
cmp eax, 0
jne .lp
cmp dword [ebp-4], 1
jne .not_negative2
mov byte [edi+ecx], '-'
inc ecx
.not_negative2:
push ecx ; save string length
dec ecx
xor ebx, ebx
.lp2:
mov al, [edi+ebx] ; swap one byte at each end
mov dl, [edi+ecx]
mov [edi+ebx], dl
mov [edi+ecx], al
inc ebx
dec ecx
cmp ebx, ecx
jl .lp2
pop eax ; string length, including sign
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret
PROGRAMS = tree-01
ASSEMBLY = tree-00
ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)
CC = gcc
CFLAGS = -g -Wall -O0
NASM = nasm
NASMFLAGS = -f elf64 -g
LD = ld
ASLDFLAGS = -m elf_x86_64 -e _start
.PHONY: all clean
all: $(PROGRAMS) $(ASSEMBLY)
$(PROGRAMS): %: %.c
$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $< $(LDLIBS) -o $@
%.o: %.asm calls.inc
$(NASM) $(NASMFLAGS) $< -o $@
$(ASSEMBLY): %: %.o $(AOBJMODULES)
$(LD) $(ASLDFLAGS) $^ -o $@
clean:
$(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
%ifndef CALLS_INC
%define CALLS_INC
%macro pbegin 1-*
; procedure header < (sub, reg1, reg2, reg3, ...)
; Keep rsp divisible by 16 before calling another function.
push rbp
mov rbp, rsp
sub rsp, %1
%rep %0 - 1
%rotate 1
push %1
%endrep
%endmacro
%macro pend 0-*
; procedure tail < (reg1, reg2, reg3, ...)
%rep %0
%rotate -1
pop %1
%endrep
mov rsp, rbp
pop rbp
ret
%endmacro
%macro pcall 1-7
; System V call < (name, param1, ..., param6)
; Integer/pointer arguments only. Use 64-bit registers or qword memory.
; Capture operands before changing argument registers; no RSP operands.
; The caller must already have aligned RSP to 16 bytes.
%rep %0 - 1
%rotate -1
push qword %1
%endrep
%rotate -1
%if %0 > 1
pop rdi
%endif
%if %0 > 2
pop rsi
%endif
%if %0 > 3
pop rdx
%endif
%if %0 > 4
pop rcx
%endif
%if %0 > 5
pop r8
%endif
%if %0 > 6
pop r9
%endif
call %1
%endmacro
%macro scall 1-4 0, 0, 0
; system call
; < (syscall number, param1, param2, param3) > rax
push rdi
push rsi
push rdx
push rcx
push r11
push qword %4
push qword %3
push qword %2
pop rdi
pop rsi
pop rdx
mov eax, %1
syscall
pop r11
pop rcx
pop rdx
pop rsi
pop rdi
%endmacro
%endif
%include "calls.inc"
global sint2str
section .text
sint2str:
; (signed int: edi, result: rsi) -> length in rax
pbegin 0, rbx
mov eax, edi ; edi keeps the original sign
cmp eax, 0
jge .not_negative
neg eax ; unsigned magnitude, including INT_MIN
.not_negative:
mov ebx, 10
xor rcx, rcx
.lp:
xor edx, edx
div ebx
add dl, '0'
mov [rsi+rcx], dl
inc ecx
test eax, eax
jne .lp
cmp edi, 0
jge .reverse
mov byte [rsi+rcx], '-'
inc ecx
.reverse:
push rcx ; save length
dec ecx
xor rbx, rbx
.lp2:
cmp ebx, ecx
jge .end
mov al, [rsi+rbx]
mov dl, [rsi+rcx]
mov [rsi+rbx], dl
mov [rsi+rcx], al
inc ebx
dec ecx
jmp .lp2
.end:
pop rax
pend rbx
%include "calls.inc"
%assign stack_len 1024
%assign num_len 12 ; sign + 10 digits + space
%assign start 0
%assign left_visited 1
%assign completed 2
%assign node_val 0 ; 4-byte int, then 4 bytes of padding
%assign node_left 8 ; 8-byte pointer
%assign node_right 16 ; 8-byte pointer
%assign node_size 24
%assign stack_p 0
%assign stack_st 8
%assign stack_size 16
%macro stack_push 3 ; (size_operand, node_pointer, state)
inc dword %1
push qword %3
push qword %2
%endmacro
%macro stack_pop 1 ; (size_operand)
dec dword %1
add rsp, stack_size
%endmacro
global _start
extern sint2str
section .data
new_line db 10
section .text
print_int:
; (val: edi)
pbegin 16, rbx, r12 ; buffer + padding = 16 bytes
lea rbx, [rbp-num_len]
pcall sint2str, rdi, rbx
mov byte [rbx+rax], ' '
lea r12, [rax+1] ; length including space
.write:
scall 1, 1, rbx, r12
cmp rax, -4 ; interrupted: retry
je .write
test rax, rax
jle .error
add rbx, rax
sub r12, rax
jne .write
pend rbx, r12
.error:
scall 60, 3
tree_push:
; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
pbegin 0
mov eax, [rdx]
imul rax, node_size
add rax, rsi ; tmp = &nodes[*nodes_used]
inc dword [rdx]
mov [rax+node_val], ecx
mov qword [rax+node_left], 0
mov qword [rax+node_right], 0
mov [rdi], rax ; *p = tmp
pend
tree_insert:
; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
pbegin 0
mov rax, [rdi]
test rax, rax
je .new_node
cmp ecx, [rax+node_val]
jl .left
jg .right
jmp .end
.new_node:
pcall tree_push, rdi, rsi, rdx, rcx
jmp .end
.left:
lea rax, [rax+node_left]
pcall tree_insert, rax, rsi, rdx, rcx
jmp .end
.right:
lea rax, [rax+node_right]
pcall tree_insert, rax, rsi, rdx, rcx
.end:
pend
tree_print1:
; (p: rdi)
pbegin 8, rbx ; padding + saved rbx = 16 bytes
mov rbx, rdi
test rbx, rbx
je .end
pcall tree_print1, [rbx+node_left]
mov eax, [rbx+node_val]
pcall print_int, rax
pcall tree_print1, [rbx+node_right]
.end:
pend rbx
tree_print:
; (p: rdi)
; [rbp-4] = size, rbx = current traversal record
pbegin 8, rbx
mov dword [rbp-4], 0
test rdi, rdi
je .end
stack_push [rbp-4], rdi, start
.lp:
cmp dword [rbp-4], 0
je .end
mov rbx, rsp
mov eax, [rbx+stack_st]
cmp eax, start
je .start
cmp eax, left_visited
je .left_visited
.completed:
stack_pop [rbp-4]
jmp .lp
.start:
mov dword [rbx+stack_st], left_visited
mov rax, [rbx+stack_p]
mov rax, [rax+node_left]
test rax, rax
je .lp
stack_push [rbp-4], rax, start
jmp .lp
.left_visited:
mov rax, [rbx+stack_p]
mov eax, [rax+node_val]
pcall print_int, rax
mov dword [rbx+stack_st], completed
mov rax, [rbx+stack_p]
mov rax, [rax+node_right]
test rax, rax
je .lp
stack_push [rbp-4], rax, start
jmp .lp
.end:
pend rbx
_start:
; [rbp-8] = p, [rbp-12] = nodes_used
; [rbp-(16+stack_len*node_size)] = nodes[0]
mov rbp, rsp
sub rsp, 16+stack_len*node_size
mov qword [rbp-8], 0
mov dword [rbp-12], 0
lea rbx, [rbp-8]
lea r12, [rbp-(16 + stack_len * node_size)]
lea r13, [rbp-12]
pcall tree_insert, rbx, r12, r13, 1
pcall tree_insert, rbx, r12, r13, 3
pcall tree_insert, rbx, r12, r13, 2
pcall tree_print, [rbp-8]
lea rax, [rel new_line]
scall 1, 1, rax, 1
scall 60, 0
#include <stdio.h>
enum { stack_len = 1024 };
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
};
void stack_push(struct stack *s, int *size,
const struct node *p, const enum state st)
{
struct stack *tmp = &s[*size];
(*size)++;
tmp->p = p;
tmp->st = st;
}
void stack_pop(int *size)
{
(*size)--;
}
void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
struct node *tmp = &nodes[*nodes_used];
(*nodes_used)++;
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
if (!*p)
tree_push(p, nodes, nodes_used, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, nodes, nodes_used, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, nodes, nodes_used, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack backpath[stack_len], *s;
int size = 0;
if (!p)
return;
stack_push(backpath, &size, p, start);
while (size) {
s = &backpath[size - 1];
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(backpath, &size, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(backpath, &size, s->p->right, start);
break;
case completed:
stack_pop(&size);
}
}
}
int main(void)
{
struct node *p, nodes[stack_len];
int nodes_used;
p = NULL;
nodes_used = 0;
tree_insert(&p, nodes, &nodes_used, 1);
tree_insert(&p, nodes, &nodes_used, 3);
tree_insert(&p, nodes, &nodes_used, 2);
tree_print(p);
printf("\n");
return 0;
}
Simple, mutual, branching, and nested recursion create different dependency patterns. Array and tree sums provide practical examples, while Ackermann's function illustrates nested calls whose rapid growth makes direct evaluation expensive.
A linear recursion makes one call per level:
int array_sum2(const int *arr, int len)
{
return len <= 0 ? 0 : *arr + array_sum2(arr + 1, len - 1);
}
A parallel recursion makes several calls per level, as in a tree:
struct node {
int val;
struct node *left, *right;
};
int tree_sum(const struct node *p)
{
return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
factorial is a common teaching example, but not always a useful practical one
binomial coefficients need not be computed through large factorials
author prefers examples whose recursive structure arises in ordinary tasks
array sum:
simple recursion: one recursive continuation per invocation
nested recursion: a recursive result becomes input to another recursive call
PROGRAMS = parallel
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *left, *right;
};
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print(const struct node *p)
{
if (!p)
return;
tree_print(p->left);
printf("%d ", p->val);
tree_print(p->right);
}
int tree_sum(const struct node *p)
{
return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
int main()
{
struct node *p;
p = NULL;
tree_insert(&p, 1);
tree_insert(&p, 3);
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_print(p);
printf("\n");
int sum = tree_sum(p);
printf("%d\n", sum);
return 0;
}
#include <stdio.h>
int array_sum1(const int arr[], int len)
{
if (len <= 0)
return 0;
return arr[0] + array_sum1(&(arr[1]), len - 1);
}
int array_sum2(const int *arr, int len)
{
return len <= 0 ? 0 : *arr + array_sum2(arr + 1, len - 1);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(*arr);
int sum1 = array_sum1(arr, len);
int sum2 = array_sum2(arr, len);
printf("%d %d\n", sum1, sum2);
return 0;
}
A fold combines sequence elements with a seed and a supplied operation. Left and right folds group operands differently, which changes results for some operations and determines whether recursive calls leave work pending.
Left and right folds over a list, with the combining function as a parameter:
typedef int (*funptr)(int, int);
struct item {
int val;
struct item *next;
};
int list_reduce_l(funptr f, int i, struct item *l)
{
return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}
int list_reduce_r(funptr f, int i, struct item *l)
{
return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}
The same folds compute a sum, a product, a maximum and a count by changing only the function:
#include <stdio.h>
#include <stdlib.h>
typedef int (*funptr)(int, int);
struct item {
int val;
struct item *next;
};
void item_push(struct item **p, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
void item_pop(struct item **p)
{
struct item *tmp = *p;
(*p) = (*p)->next;
free(tmp);
}
int list_reduce_l1(funptr f, int i, struct item *l)
{
int new_i;
if (!l)
return i;
new_i = f(i, l->val);
return list_reduce_l1(f, new_i, l->next);
}
int list_reduce_r1(funptr f, int i, struct item *l)
{
int rest_res;
if (!l)
return i;
rest_res = list_reduce_r1(f, i, l->next);
return f(l->val, rest_res);
}
int list_reduce_l(funptr f, int i, struct item *l)
{
return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}
int list_reduce_r(funptr f, int i, struct item *l)
{
return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}
int plus(int x, int y) { return x + y; }
int mul(int x, int y) { return x * y; }
int max(int x, int y) { return x > y ? x : y; }
int zero_count_l(int n, int x) { return x == 0 ? n + 1 : n; }
int zero_count_r(int x, int n) { return x == 0 ? n + 1 : n; }
int main()
{
int sum, product, maximum, num_zeros;
struct item *p = NULL;
item_push(&p, 1);
item_push(&p, 2);
item_push(&p, 3);
item_push(&p, 0);
item_push(&p, 4);
sum = list_reduce_l(plus, 0, p);
product = list_reduce_l(mul, 1, p);
maximum = list_reduce_l(max, p->val, p->next);
num_zeros = list_reduce_l(zero_count_l, 0, p);
sum = list_reduce_r(plus, 0, p);
product = list_reduce_r(mul, 1, p);
maximum = list_reduce_r(max, p->val, p->next);
num_zeros = list_reduce_r(zero_count_r, 0, p);
printf("sum: %d\n", sum);
printf("mul: %d\n", product);
printf("max: %d\n", maximum);
printf("num zeros: %d\n", num_zeros);
return 0;
}
sum: 10
mul: 0
max: 4
num zeros: 1
fold combines sequence elements with an initial accumulator/seed
left fold groups from the left:
recursion expresses the dependency structure of folds
C illustration uses integer nodes and intfunptr = int (*)(int,int)
right fold must wait for the tail result before calling f
left-fold recursive call is in tail position
supply arithmetic helpers as fold arguments
zero-counting helper must match operand order
examples illustrate the abstraction rather than prescribing a C optimization
#include <stdio.h>
#include <stdlib.h>
struct item {
int val;
struct item *next;
};
typedef int (*intfunptr)(int, int);
#ifdef SHORT_VERS
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}
#else
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
int new_i;
if(!ls)
return i;
new_i = f(i, ls->val);
return intlist_reduce_l(f, new_i, ls->next);
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
int rest_res;
if(!ls)
return i;
rest_res = intlist_reduce_r(f, i, ls->next);
return f(ls->val, rest_res);
}
#endif
int int_plus(int x, int y) { return x + y; }
int int_mul(int x, int y) { return x * y; }
int int_max(int x, int y) { return x > y ? x : y; }
int int_zcnt_left(int n, int x) { return x==0 ? n+1 : n; }
int int_zcnt_right(int x, int n) { return x==0 ? n+1 : n; }
struct item* array2list(int *a, int n)
{
struct item *p;
if(!n)
return NULL;
p = malloc(sizeof(*p));
p->val = *a;
p->next = array2list(a+1, n-1);
return p;
}
void freelist(struct item *p)
{
if(!p)
return;
freelist(p->next);
free(p);
}
int main()
{
int s, p, ma, mb, z1, z2;
int a[] = { 1,2,3,4,5,6,7,8 };
int b[] = { 1,2,0,13,4,15,61,7,0,8 };
struct item *lsa = array2list(a, 8);
struct item *lsb = array2list(b, 10);
#ifdef SHORT_VERS
printf("using short versions...\n");
#endif
s = intlist_reduce_l(int_plus, 0, lsa);
p = intlist_reduce_l(int_mul, 1, lsa);
printf("%d %d\n", s, p);
s = intlist_reduce_l(int_plus, 0, lsb);
p = intlist_reduce_l(int_mul, 1, lsb);
printf("%d %d\n", s, p);
s = intlist_reduce_r(int_plus, 0, lsa);
p = intlist_reduce_r(int_mul, 1, lsa);
printf("%d %d\n", s, p);
s = intlist_reduce_r(int_plus, 0, lsb);
p = intlist_reduce_r(int_mul, 1, lsb);
printf("%d %d\n", s, p);
ma = intlist_reduce_l(int_max, lsa->val, lsa->next);
mb = intlist_reduce_l(int_max, lsb->val, lsb->next);
printf("%d %d\n", ma, mb);
z1 = intlist_reduce_l(int_zcnt_left, 0, lsb);
z2 = intlist_reduce_r(int_zcnt_right, 0, lsb);
printf("%d %d\n", z1, z2);
return 0;
}
PROGRAMS = reduce reduce_loop
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include <stdlib.h>
typedef int (*funptr)(int, int);
struct item {
int val;
struct item *next;
};
void item_push(struct item **p, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
void item_pop(struct item **p)
{
struct item *tmp = *p;
(*p) = (*p)->next;
free(tmp);
}
int list_reduce_l1(funptr f, int i, struct item *l)
{
int new_i;
if (!l)
return i;
new_i = f(i, l->val);
return list_reduce_l1(f, new_i, l->next);
}
int list_reduce_r1(funptr f, int i, struct item *l)
{
int rest_res;
if (!l)
return i;
rest_res = list_reduce_r1(f, i, l->next);
return f(l->val, rest_res);
}
int list_reduce_l(funptr f, int i, struct item *l)
{
return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}
int list_reduce_r(funptr f, int i, struct item *l)
{
return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}
int plus(int x, int y) { return x + y; }
int mul(int x, int y) { return x * y; }
int max(int x, int y) { return x > y ? x : y; }
int zero_count_l(int n, int x) { return x == 0 ? n + 1 : n; }
int zero_count_r(int x, int n) { return x == 0 ? n + 1 : n; }
int main()
{
int sum, product, maximum, num_zeros;
struct item *p = NULL;
item_push(&p, 1);
item_push(&p, 2);
item_push(&p, 3);
item_push(&p, 0);
item_push(&p, 4);
sum = list_reduce_l(plus, 0, p);
product = list_reduce_l(mul, 1, p);
maximum = list_reduce_l(max, p->val, p->next);
num_zeros = list_reduce_l(zero_count_l, 0, p);
sum = list_reduce_r(plus, 0, p);
product = list_reduce_r(mul, 1, p);
maximum = list_reduce_r(max, p->val, p->next);
num_zeros = list_reduce_r(zero_count_r, 0, p);
printf("sum: %d\n", sum);
printf("mul: %d\n", product);
printf("max: %d\n", maximum);
printf("num zeros: %d\n", num_zeros);
}
#include <stdio.h>
#include <stdlib.h>
struct item {
int val;
struct item *next;
};
typedef int (*intfunptr)(int, int);
/* the two recursive versions from the book */
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}
/* left reduction as a loop: i holds the result so far */
int intlist_reduce_l_loop(intfunptr f, int i, struct item *ls)
{
for (; ls; ls = ls->next)
i = f(i, ls->val);
return i;
}
/* right reduction as a loop: possible for an array, walked backwards */
int intarray_reduce_r_loop(intfunptr f, int i, const int *arr, int len)
{
int k;
for (k = len - 1; k >= 0; k--)
i = f(arr[k], i);
return i;
}
void push(struct item **ls, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *ls;
*ls = tmp;
}
void pop(struct item **ls)
{
struct item *tmp = *ls;
*ls = (*ls)->next;
free(tmp);
}
/* ... and for a list only through a reversed copy */
int intlist_reduce_r_loop(intfunptr f, int i, struct item *ls)
{
struct item *rev = NULL;
for (; ls; ls = ls->next)
push(&rev, ls->val);
while (rev) {
i = f(rev->val, i);
pop(&rev);
}
return i;
}
struct item *make_list(const int *arr, int len)
{
struct item *first = NULL;
int k;
for (k = len - 1; k >= 0; k--)
push(&first, arr[k]);
return first;
}
int sub(int x, int y) { return x - y; }
int main()
{
int arr[] = { 1, 2, 3, 4 };
struct item *ls = make_list(arr, 4), *tmp;
printf("left, recursion: %d\n", intlist_reduce_l(sub, 0, ls));
printf("left, loop: %d\n", intlist_reduce_l_loop(sub, 0, ls));
printf("right, recursion: %d\n", intlist_reduce_r(sub, 0, ls));
printf("right, array: %d\n", intarray_reduce_r_loop(sub, 0, arr, 4));
printf("right, list: %d\n", intlist_reduce_r_loop(sub, 0, ls));
while (ls) {
tmp = ls;
ls = ls->next;
free(tmp);
}
return 0;
}
A tail call returns its callee's result without further work, allowing implementations to reuse the current frame. Accumulators expose tail positions, but unresolved branches still require storage, and C does not guarantee tail-call optimization.
list_len must add 1 after its recursive call returns.
list_len_do1 carries the count in an accumulator, so its
recursive call is the last action: a tail call:
struct item {
int val;
struct item *next;
};
int list_len(const struct item *p)
{
return p ? list_len(p->next) + 1 : 0;
}
int list_len_do1(const struct item *p, int count)
{
return p ? list_len_do1(p->next, count + 1) : count;
}
int list_len1(const struct item *p)
{
return list_len_do1(p, 0);
}
recursive list search:
self-tail-call can be modeled as updating parameters and restarting the body
an ordinary loop expresses the same repeated search
wildcard matcher uses match and starmatch
ordinary character / ? case:
leading * delegates to starmatch
first try matching the star against an empty substring
failed alternative does not yet mean complete failure
only unresolved alternatives need retained continuation state
last alternative needs no retry state
if all eligible tail calls were optimized, retained frames would represent unresolved stars rather than every consumed character
recognizing tail position does not promise a particular machine-code result
reusing a frame must preserve arguments still needed to compute new ones
optimizers balance execution cost and resource use
list_length(next) + 1 is not itself a tail call
accumulator parameter moves pending work before the recursive call
an accumulator cannot erase every outstanding branch
#include <stdio.h>
int starmatch(const char *str, const char *pat);
int match(const char *str, const char *pat)
{
switch(*pat) {
case 0:
return *str == 0;
case '*':
return starmatch(str, pat+1);
default:
if(!*str || (*str != *pat && *pat != '?'))
return 0;
return
match(str+1, pat+1);
}
}
#if 1
int starmatch(const char *str, const char *pat)
{
if(match(str, pat))
return 1;
if(!*str)
return 0;
return starmatch(str+1, pat);
}
#else
int starmatch(const char *str, const char *pat)
{
if(!*str)
return match("", pat);
if(match(str, pat))
return 1;
return starmatch(str+1, pat);
}
#endif
int main(int argc, const char **argv)
{
if(argc < 3) {
printf("Need two arguments\n");
return 1;
}
if(match(argv[1], argv[2]))
printf("YES\n");
else
printf("NO\n");
return 0;
}
PROGRAMS = accumulator reverse reverse1 reverse2 tree_sum
SRCMODULES = list.c tree.c
OBJMODULES = $(SRCMODULES:.c=.o)
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include "list.h"
int list_len(const struct item *p)
{
return p ? list_len(p->next) + 1 : 0;
}
int list_len_do1(const struct item *p, int count)
{
return p ? list_len_do1(p->next, count + 1) : count;
}
int list_len1(const struct item *p)
{
return list_len_do1(p, 0);
}
int array_sum_do(int *arr, int len, int sum)
{
return len ? array_sum_do(arr + 1, len - 1, sum + *arr) : sum;
}
int array_sum(int *arr, int len)
{
return array_sum_do(arr, len, 0);
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int len = sizeof(arr) / sizeof(*arr);
int sum = array_sum(arr, len);
printf("sum: %d\n", sum);
struct item *p = NULL;
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
int len0 = list_len(p);
printf("len: %d\n", len0);
int len1 = list_len(p);
printf("len1: %d\n", len1);
list_pop(&p);
list_pop(&p);
list_pop(&p);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void list_push(struct item **p, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
int list_pop(struct item **p)
{
struct item *tmp = *p;
int val = tmp->val;
*p = (*p)->next;
free(tmp);
return val;
}
void list_print(const struct item *p)
{
for (; p; p = p->next)
printf("%d ", p->val);
printf("\n");
}
struct item {
int val;
struct item *next;
};
void list_push(struct item **p, int val);
int list_pop(struct item **p);
void list_print(const struct item *p);
#include <stdio.h>
int starmatch(const char *str, const char *pat);
int match(const char *pat, const char *str)
{
switch (*pat) {
case 0:
return *str == 0;
case '*':
return starmatch(pat + 1, str);
default:
if (!*str || (*str != *pat && *pat != '?'))
return 0;
return match(pat + 1, str + 1);
}
}
int starmatch(const char *pat, const char *str)
{
if (match(pat, str))
return 1;
if (!*str)
return 0;
return starmatch(pat, str + 1);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <pattern <string>\n", argv[0]);
return 1;
}
if (match(argv[1], argv[2]))
printf("matched\n");
else
printf("does not match\n");
return 0;
}
#include <stdio.h>
#include "list.h"
struct item *list_reverse_do(struct item *dst, struct item *src)
{
struct item *tmp;
if (!src)
return dst;
tmp = src->next;
src->next = dst;
return list_reverse_do(src, tmp);
}
struct item *list_reverse(struct item *src)
{
return list_reverse_do(NULL, src);
}
int main()
{
struct item *p = NULL;
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
struct item *rev = list_reverse(p);
list_print(rev);
list_pop(&rev);
list_pop(&rev);
list_pop(&rev);
return 0;
}
#include <stdio.h>
#include "list.h"
struct item *list_iterate(struct item *p)
{
return !p->next ? p : list_iterate(p->next);
}
struct item *list_reverse(struct item *p)
{
struct item *rev, *last;
if (!p || !p->next)
return p;
rev = list_reverse(p->next);
last = list_iterate(rev);
last->next = p;
p->next = NULL;
return rev;
}
int main()
{
struct item *p = NULL;
list_push(&p, 4);
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
list_print(p);
struct item *rev = list_reverse(p);
list_print(rev);
return 0;
}
#include <stdio.h>
#include "list.h"
struct item *list_reverse(struct item *curr)
{
struct item *prev, *next;
for (prev = NULL; curr; prev = curr, curr = next) {
next = curr->next;
curr->next = prev;
}
return prev;
}
struct item *list_reverse1(struct item *p)
{
struct item *rev;
if (!p || !p->next)
return p;
rev = list_reverse1(p->next);
p->next->next = p;
p->next = NULL;
return rev;
}
int main()
{
struct item *p = NULL;
list_push(&p, 4);
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
list_print(p);
struct item *rev = list_reverse1(p);
list_print(rev);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print(const struct node *p)
{
if (!p)
return;
tree_print(p->left);
printf("%d ", p->val);
tree_print(p->right);
}
void stack_push(struct stack **s, const struct node *p)
{
struct stack *tmp = malloc(sizeof(*tmp));
tmp->p = p;
tmp->next = *s;
*s = tmp;
}
const struct node *stack_pop(struct stack **s)
{
struct stack *tmp = *s;
const struct node *p = tmp->p;
*s = (*s)->next;
free(tmp);
return p;
}
void stack_init1(struct stack1 *s, int capacity)
{
s->p = malloc(capacity * sizeof(*s->p));
s->capacity = capacity;
s->size = 0;
}
void stack_push1(struct stack1 *s, const struct node *p)
{
if (s->size == s->capacity) {
s->capacity *= 2;
s->p = realloc(s->p, s->capacity * sizeof(*s->p));
}
s->p[s->size] = p;
s->size++;
}
const struct node *stack_pop1(struct stack1 *s)
{
s->size--;
return s->p[s->size];
}
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
struct stack *next;
};
struct stack1 {
const struct node **p;
int size;
int capacity;
};
void tree_push(struct node **p, int val);
void tree_insert(struct node **p, int val);
void tree_print(const struct node *p);
void stack_push(struct stack **s, const struct node *p);
const struct node *stack_pop(struct stack **s);
void stack_init1(struct stack1 *s, int capacity);
void stack_push1(struct stack1 *s, const struct node *p);
const struct node *stack_pop1(struct stack1 *s);
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
int tree_sum(const struct node *p)
{
return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
int tree_sum_do1(const struct node *p, int sum)
{
if (!p)
return sum;
sum = tree_sum_do1(p->left, sum);
return tree_sum_do1(p->right, sum + p->val);
}
int tree_sum1(const struct node *p)
{
return tree_sum_do1(p, 0);
}
int tree_sum_do2(const struct node *p, int sum, struct stack *s)
{
if (!p)
return sum;
if (p->left)
stack_push(&s, p->left);
if (p->right)
return tree_sum_do2(p->right, sum + p->val, s);
if (s) {
const struct node *tmp = stack_pop(&s);
return tree_sum_do2(tmp, sum + p->val, s);
}
return sum + p->val;
}
int tree_sum2(const struct node *p)
{
return tree_sum_do2(p, 0, NULL);
}
int tree_sum_do3(const struct node *p, int sum, struct stack *s)
{
if (p) {
stack_push(&s, p);
return tree_sum_do3(p->left, sum, s);
}
if (s) {
const struct node *tmp = stack_pop(&s);
return tree_sum_do3(tmp->right, sum + tmp->val, s);
}
return sum;
}
int tree_sum3(const struct node *p)
{
return tree_sum_do3(p, 0, NULL);
}
int tree_sum_do4(const struct node *p, int sum, struct stack1 *s)
{
if (p) {
stack_push1(s, p);
return tree_sum_do4(p->left, sum, s);
}
if (s->size) {
const struct node *tmp = stack_pop1(s);
return tree_sum_do4(tmp->right, sum + tmp->val, s);
}
return sum;
}
int tree_sum4(const struct node *p)
{
int sum;
struct stack1 s;
stack_init1(&s, 1);
sum = tree_sum_do4(p, 0, &s);
free(s.p);
return sum;
}
int main()
{
int sum;
struct node *p;
p = NULL;
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_insert(&p, 1);
tree_insert(&p, 4);
tree_print(p);
printf("\n");
sum = tree_sum(p);
printf("%d\n", sum);
sum = tree_sum1(p);
printf("%d\n", sum);
sum = tree_sum2(p);
printf("%d\n", sum);
sum = tree_sum3(p);
printf("%d\n", sum);
sum = tree_sum4(p);
printf("%d\n", sum);
return 0;
}
Recursive thinking can characterize a result structurally or trace actions through descent and return. A string-copy example allocates at the deepest call and fills characters while returning, showing why execution order sometimes remains essential.
Etude 9.01 states the maximum of an array recursively: the maximum of one element is that element; otherwise it is the larger of the first element and the maximum of the rest:
#include <stdio.h>
int vecmax(const int *arr, int len)
{
int submax = (len == 1 ? *arr : vecmax(arr + 1, len - 1));
return submax > *arr ? submax : *arr;
}
int main()
{
int i;
int array[] = { 2, 8, 11, 1, 9, 4, 6 };
int len = sizeof(array) / sizeof(*array);
int max = vecmax(array, len);
for (i = 0; i < len; i++)
printf("%d ", array[i]);
printf("\nmax: %d\n", max);
return 0;
}
2 8 11 1 9 4 6
max: 11
A recursive strdup learns the length only at the deepest
call, so it allocates there and stores the characters on the way
back:
char *strdup_rec_do1(const char *str, int depth)
{
char *res;
if (*str)
res = strdup_rec_do1(str + 1, depth + 1);
else
res = malloc(depth + 1);
res[depth] = *str;
return res;
}
Etude 9.06 finds a substring without loops. The checking
flag distinguishes comparing a candidate match from moving the start of
the search:
#include <stdio.h>
static const char *strstr_do(const char *str, const char *sub, int checking);
static const char *strstr_helper(const char *str, const char *sub, int checking)
{
if (checking)
return NULL;
else
return strstr_do(str + 1, sub, 0);
}
static const char *strstr_do(const char *str, const char *sub, int checking)
{
if (*str == 0)
return *sub == 0 ? str : NULL;
else if (*sub == 0)
return str;
else if (*str == *sub)
return strstr_do(str + 1, sub + 1, 1) ? str : strstr_helper(str, sub, checking);
else
return strstr_helper(str, sub, checking);
}
static char *strstr(const char *str, const char *sub)
{
return (char *) strstr_do(str, sub, 0);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <str> <sub>\n", argv[0]);
return 1;
}
const char *res = strstr(argv[1], argv[2]);
if (res != NULL)
printf("%s\n", res);
else
printf("Have not found\n");
return 0;
}
issippi
using recursive calls does not automatically mean thinking recursively
two descriptions of list length:
nested fold expressions expose the recursive structure
accumulator-based recursion often invites operational reasoning
recursive string-copy example uses descent and return phases
ordering is essential in that example
both structural and operational explanations have uses
recursion as technique: direct or indirect self-invocation
#include <stdio.h>
#include <stdlib.h>
char *strdup_rec_do(const char *str, int depth)
{
char *res;
if(*str)
res = strdup_rec_do(str+1, depth+1);
else
res = malloc(depth+1);
res[depth] = *str;
return res;
}
char *strdup_rec(const char *str)
{
return strdup_rec_do(str, 0);
}
int main(int argc, char**argv)
{
char *s = strdup_rec(argv[0]);
puts(s);
free(s);
return 0;
}
PROGRAMS = strdup_rec
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include <stdlib.h>
char *strdup_rec_do1(const char *str, int depth)
{
char *res;
if (*str)
res = strdup_rec_do1(str + 1, depth + 1);
else
res = malloc(depth + 1);
res[depth] = *str;
return res;
}
char *strdup_rec_do(const char *str, int depth)
{
char *res = *str ? strdup_rec_do(str + 1, depth + 1) : malloc(depth + 1);
res[depth] = *str;
return res;
}
char *strdup_rec(const char *str)
{
return strdup_rec_do1(str, 0);
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
return 1;
}
char *dup = strdup_rec(argv[1]);
printf("%s\n%s\n", argv[1], dup);
free(dup);
return 0;
}
Languages supply concepts as well as notation, encouraging some approaches and making others awkward. Comparing their influence on thought requires looking beyond surface syntax to expression semantics and practical delivery constraints.
Available operations can suggest better algorithms, as sorting repeated sequence windows replaces pairwise comparison. A language can require, encourage, merely permit, or impede a paradigm without uniquely determining the programmer's solution.
language supplies concepts as well as notation for expressing a solution
alternative uses a sortable collection of windows
algorithmic improvement can dominate implementation overhead
language communities develop habits and conventions
one paradigm label rarely describes an entire language
book proposes seven relationships between a language and a paradigm:
illustrative classifications from the author
C++ offers several independently useful models
having a feature is distinct from making it the preferred style
a skilled programmer can impose conventions beyond direct syntax support
C macro-based generic code can be cumbersome
historical languages without localized subprogram state restrict recursion
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test
SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)
CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include "matrix.h"
#include "apl.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
int i;
for (i = 0; i < rows - 1; i++)
if (array_compare(a[i], a[i+1], min) == 0) {
array_push(res, a[i][min]);
array_push(res, a[i+1][min]);
}
}
#ifndef APL_H
#define APL_H
#include "array.h"
#include "matrix.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
#include "apl.h"
int main()
{
struct array res;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(*arr);
int rows = len - min + 1;
int (*matrix)[cols] = malloc(rows * sizeof(*matrix));
matrix_create(arr, len, matrix);
matrix_print(matrix, rows);
printf("\n");
matrix_merge_sort(matrix, 0, rows - 1);
matrix_print(matrix, rows);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
void array_init(struct array *p, int capacity)
{
p->a = malloc(capacity * sizeof(*p->a));
p->capacity = capacity;
p->size = 0;
}
void array_push(struct array *p, int val)
{
int i;
for (i = 0; i < p->size; i++)
if (p->a[i] == val)
return;
if (p->capacity == p->size) {
p->capacity *= 2;
p->a = realloc(p->a, p->capacity * sizeof(*p->a));
}
p->a[p->size] = val;
p->size++;
}
void array_pop(struct array *p, int *val)
{
p->size--;
*val = p->a[p->size];
}
void array_clean(struct array *p)
{
free(p->a);
p->capacity = 0;
p->size = 0;
}
void array_print(struct array p)
{
int i;
for (i = 0; i < p.size; i++)
printf("%d ", p.a[i]);
printf("\n");
}
void array_copy(int *dst, const int *src, int n)
{
int i;
for (i = 0; i < n; i++)
dst[i] = src[i];
}
int array_compare(const int *a, const int *b, int n)
{
int i;
for (i = 0; i < n && a[i] == b[i]; i++)
{}
if (i == n)
return 0;
return a[i] < b[i] ? -1 : 1;
}
#ifndef ARRAY_H
#define ARRAY_H
struct array {
int *a;
int size;
int capacity;
};
void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
void array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);
void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);
#endif
#include <stdlib.h>
#include "dna.h"
static int random_number(double limit)
{
return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}
void dna_generate(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
a[i] = random_number(DIFF_DNA);
}
#ifndef DNA_H
#define DNA_H
#define DIFF_DNA 4.0
enum {
dna_len = 100000
};
void dna_generate(int *a, int n);
#endif
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "apl.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int (*matrix)[cols];
int len = dna_len;
int rows = len - min + 1;
dna = malloc(len * sizeof(*dna));
matrix = malloc(rows * sizeof(*matrix));
srand(time(NULL));
dna_generate(dna, dna_len);
matrix_create(dna, len, matrix);
matrix_merge_sort(matrix, 0, rows - 1);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
return 0;
}
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "fortran.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int min = 6;
dna = malloc(dna_len * sizeof(*dna));
srand(time(NULL));
dna_generate(dna, dna_len);
array_init(&res, 1);
fortran_find_repeating(dna, dna_len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
#include "array.h"
void fortran_find_repeating(int *arr, int len, int min, struct array *res)
{
int i, j, k, found;
for (i = 0; i < len - min; i++) {
for (j = i + 1; j < len - min + 1; j++) {
found = 1;
for (k = 0; k < min; k++)
if (arr[i+k] != arr[j+k]) {
found = 0;
break;
}
if (found) {
array_push(res, i);
array_push(res, j);
}
}
}
}
#ifndef FORTRAN_H
#define FORTRAN_H
#include "array.h"
void fortran_find_repeating(int *arr, int len, int min, struct array *res);
#endif
#include "array.h"
#include "fortran.h"
int main()
{
struct array res;
int min = 5;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(arr[0]);
array_init(&res, 1);
fortran_find_repeating(arr, len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
void matrix_create(int *arr, int len, int (*a)[cols])
{
int i, j;
int rows = len - min + 1;
if (len < min)
return;
for (i = 0; i < rows; i++) {
for (j = 0; j < min; j++)
a[i][j] = arr[i + j];
a[i][j] = i;
}
}
void matrix_print(int (*a)[cols], int rows)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%3d ", a[i][j]);
printf("\n");
}
}
static void matrix_merge(int (*a)[cols], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int (*L)[cols] = malloc(n1 * sizeof(*L));
int (*R)[cols] = malloc(n2 * sizeof(*R));
for (i = 0; i < n1; i++)
array_copy(L[i], a[l + i], cols);
for (j = 0; j < n2; j++)
array_copy(R[j], a[m + 1 + j], cols);
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (array_compare(L[i], R[j], min) <= 0) {
array_copy(a[k], L[i], cols);
i++;
} else {
array_copy(a[k], R[j], cols);
j++;
}
for (; i < n1; i++, k++)
array_copy(a[k], L[i], cols);
for (; j < n2; j++, k++)
array_copy(a[k], R[j], cols);
free(L);
free(R);
}
void matrix_merge_sort(int (*a)[cols], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
matrix_merge_sort(a, l, m);
matrix_merge_sort(a, m + 1, r);
matrix_merge(a, l, m, r);
}
}
#ifndef MATRIX_H
#define MATRIX_H
enum {
min = 5,
cols = min + 1
};
void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);
#endif
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
for (; i < n1; i++, k++)
arr[k] = L[i];
for (; j < n2; j++, k++)
arr[k] = R[j];
}
void merge_sort(int arr[], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
merge_sort(arr, l, m);
merge_sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
int i;
int arr[] = {38, 27, 43, 10};
int len = sizeof(arr) / sizeof(*arr);
merge_sort(arr, 0, len - 1);
for (i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test
SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)
HEADERS = $(wildcard *.h)
CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic
.PHONY: all clean
all: $(PROGRAMS) merge_sort
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES) $(HEADERS)
$(CC) $(CFLAGS) $(filter-out %.h,$^) -o $@
merge_sort: merge_sort.c
$(CC) $(CFLAGS) $< -o $@
clean:
rm -f *.o $(PROGRAMS) merge_sort
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
#include "apl.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
int i;
char *seen;
if (rows < 2)
return;
seen = calloc(rows, 1);
if (!seen) {
fprintf(stderr, "apl_find_repeating: out of memory\n");
exit(1);
}
for (i = 0; i < rows - 1; i++)
if (array_compare(a[i], a[i+1], min) == 0) {
seen[a[i][min]] = 1;
seen[a[i+1][min]] = 1;
}
for (i = 0; i < rows; i++)
if (seen[i])
array_push(res, i);
free(seen);
}
#ifndef APL_H
#define APL_H
#include "array.h"
#include "matrix.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
#include "apl.h"
int main()
{
struct array res;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(*arr);
int rows = len - min + 1;
int (*matrix)[cols] = malloc(rows * sizeof(*matrix));
if (!matrix) {
fprintf(stderr, "out of memory\n");
return 1;
}
matrix_create(arr, len, matrix);
matrix_print(matrix, rows);
printf("\n");
matrix_merge_sort(matrix, 0, rows - 1);
matrix_print(matrix, rows);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
void array_init(struct array *p, int capacity)
{
if (capacity < 1)
capacity = 1;
p->a = malloc(capacity * sizeof(*p->a));
if (!p->a) {
fprintf(stderr, "array_init: out of memory\n");
exit(1);
}
p->capacity = capacity;
p->size = 0;
}
void array_push(struct array *p, int val)
{
int *tmp;
int capacity;
if (p->capacity == p->size) {
capacity = p->capacity > 0 ? p->capacity * 2 : 1;
tmp = realloc(p->a, capacity * sizeof(*p->a));
if (!tmp) {
fprintf(stderr, "array_push: out of memory\n");
exit(1);
}
p->a = tmp;
p->capacity = capacity;
}
p->a[p->size] = val;
p->size++;
}
int array_pop(struct array *p, int *val)
{
if (p->size == 0)
return 0;
p->size--;
*val = p->a[p->size];
return 1;
}
void array_clean(struct array *p)
{
free(p->a);
p->a = NULL;
p->capacity = 0;
p->size = 0;
}
void array_print(struct array p)
{
int i;
for (i = 0; i < p.size; i++)
printf("%d ", p.a[i]);
printf("\n");
}
void array_copy(int *dst, const int *src, int n)
{
int i;
for (i = 0; i < n; i++)
dst[i] = src[i];
}
int array_compare(const int *a, const int *b, int n)
{
int i;
for (i = 0; i < n && a[i] == b[i]; i++)
{}
if (i == n)
return 0;
return a[i] < b[i] ? -1 : 1;
}
#ifndef ARRAY_H
#define ARRAY_H
struct array {
int *a;
int size;
int capacity;
};
void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
int array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);
void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);
#endif
#include <stdlib.h>
#include "dna.h"
static int random_number(double limit)
{
return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}
void dna_generate(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
a[i] = random_number(DIFF_DNA);
}
#ifndef DNA_H
#define DNA_H
#define DIFF_DNA 4.0
enum {
dna_len = 100000
};
void dna_generate(int *a, int n);
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "apl.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int (*matrix)[cols];
int len = dna_len;
int rows = len - min + 1;
dna = malloc(len * sizeof(*dna));
matrix = malloc(rows * sizeof(*matrix));
if (!dna || !matrix) {
fprintf(stderr, "out of memory\n");
return 1;
}
srand(time(NULL));
dna_generate(dna, dna_len);
matrix_create(dna, len, matrix);
matrix_merge_sort(matrix, 0, rows - 1);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
free(dna);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "fortran.h"
#include "matrix.h" /* min: same window length as the APL version */
#include "dna.h"
int main()
{
struct array res;
int *dna;
dna = malloc(dna_len * sizeof(*dna));
if (!dna) {
fprintf(stderr, "out of memory\n");
return 1;
}
srand(time(NULL));
dna_generate(dna, dna_len);
array_init(&res, 1);
fortran_find_repeating(dna, dna_len, min, &res);
array_print(res);
array_clean(&res);
free(dna);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "fortran.h"
void fortran_find_repeating(const int *arr, int len, int min, struct array *res)
{
int i, j, k;
int nwin = len - min + 1;
char *seen;
if (nwin < 2)
return;
seen = calloc(nwin, 1);
if (!seen) {
fprintf(stderr, "fortran_find_repeating: out of memory\n");
exit(1);
}
for (i = 0; i < len - min; i++) {
for (j = i + 1; j < len - min + 1; j++) {
for (k = 0; k < min; k++)
if (arr[i+k] != arr[j+k])
break;
if (k == min) {
seen[i] = 1;
seen[j] = 1;
}
}
}
for (i = 0; i < nwin; i++)
if (seen[i])
array_push(res, i);
free(seen);
}
#ifndef FORTRAN_H
#define FORTRAN_H
#include "array.h"
void fortran_find_repeating(const int *arr, int len, int min, struct array *res);
#endif
#include "array.h"
#include "fortran.h"
int main()
{
struct array res;
int min = 5;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(arr[0]);
array_init(&res, 1);
fortran_find_repeating(arr, len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
void matrix_create(int *arr, int len, int (*a)[cols])
{
int i, j;
int rows = len - min + 1;
if (len < min)
return;
for (i = 0; i < rows; i++) {
for (j = 0; j < min; j++)
a[i][j] = arr[i + j];
a[i][min] = i;
}
}
void matrix_print(int (*a)[cols], int rows)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%3d ", a[i][j]);
printf("\n");
}
}
static void matrix_merge(int (*a)[cols], int (*tmp)[cols], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int (*L)[cols] = tmp;
int (*R)[cols] = tmp + n1;
for (i = 0; i < n1; i++)
array_copy(L[i], a[l + i], cols);
for (j = 0; j < n2; j++)
array_copy(R[j], a[m + 1 + j], cols);
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (array_compare(L[i], R[j], min) <= 0) {
array_copy(a[k], L[i], cols);
i++;
} else {
array_copy(a[k], R[j], cols);
j++;
}
for (; i < n1; i++, k++)
array_copy(a[k], L[i], cols);
for (; j < n2; j++, k++)
array_copy(a[k], R[j], cols);
}
static void matrix_merge_sort_rec(int (*a)[cols], int (*tmp)[cols],
int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
matrix_merge_sort_rec(a, tmp, l, m);
matrix_merge_sort_rec(a, tmp, m + 1, r);
matrix_merge(a, tmp, l, m, r);
}
}
void matrix_merge_sort(int (*a)[cols], int l, int r)
{
int (*tmp)[cols];
if (l >= r)
return;
tmp = malloc((r - l + 1) * sizeof(*tmp));
if (!tmp) {
fprintf(stderr, "matrix_merge_sort: out of memory\n");
exit(1);
}
matrix_merge_sort_rec(a, tmp, l, r);
free(tmp);
}
#ifndef MATRIX_H
#define MATRIX_H
enum {
min = 5,
cols = min + 1
};
void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);
#endif
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int tmp[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int *L = tmp;
int *R = tmp + n1;
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
for (; i < n1; i++, k++)
arr[k] = L[i];
for (; j < n2; j++, k++)
arr[k] = R[j];
}
void merge_sort_rec(int arr[], int tmp[], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
merge_sort_rec(arr, tmp, l, m);
merge_sort_rec(arr, tmp, m + 1, r);
merge(arr, tmp, l, m, r);
}
}
void merge_sort(int arr[], int l, int r)
{
int *tmp;
if (l >= r)
return;
tmp = malloc((r - l + 1) * sizeof(*tmp));
if (!tmp) {
fprintf(stderr, "merge_sort: out of memory\n");
exit(1);
}
merge_sort_rec(arr, tmp, l, r);
free(tmp);
}
int main()
{
int i;
int arr[] = {38, 27, 43, 10};
int len = sizeof(arr) / sizeof(*arr);
merge_sort(arr, 0, len - 1);
for (i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
C makes assignment and other effects part of expressions, whereas Pascal more visibly separates actions from calculated values. Input loops can benefit from combined retrieval and testing, but compact idioms can obscure effects such as process creation.
Both functions copy a string. The first uses the classic C idiom, in which the loop condition does all the work through side effects; the second keeps the condition free of them:
void wrong(char *dest, const char *src)
{
while ((*dest++ = *src++));
}
void correct(char *dest, const char *src)
{
for (; *src; src++, dest++)
*dest = *src;
*dest = 0;
}
Pascal expressions cannot change variables, so only the second form exists there:
program loop_side_effects_pas;
procedure correct(var dest: string; src: string);
var
i: integer;
begin
SetLength(dest, length(src));
for i := 1 to length(src) do
dest[i] := src[i]
end;
var
src, dest: string;
begin
src := 'hello';
correct(dest, src);
writeln(src, ' ', dest)
end.
hello hello
C and Pascal share many imperative constructs
more substantial differences include:
book values C's separation between core syntax and library facilities
many such facilities could be added to another dialect or implementation
author identifies treatment of side effects as the central conceptual difference
book adopts a narrow, expression-centered definition of side effect
within that definition, expression evaluation has a side effect if it changes something observable beyond producing its value
C assignment is an expression
Pascal assignment is a statement, not a subexpression
Pascal expressions can still call effectful functions
Pascal distinguishes procedure calls from value-returning function calls
C uses functions, including void functions, for both roles
void call has no result value but can perform effects
compact copy idiom combines assignment and two pointer increments
some loops naturally follow retrieve -> test -> process
another form uses an indefinite loop and an explicit break
choice among these forms is partly a readability decision
author does not generalize that exception to every effectful condition
waiting without per-child processing is action -> test
array[i++] = value combines storing and advancing
action-oriented functions often return status or another result in C
book's Pascal rule allows effectful retrieval where it clarifies an input loop
translating that rule to C requires exceptions
experience with another language can make a style rule's motivation clearer
author argues that C makes mixing actions into expressions particularly easy
this reasoning influenced changes between the book's editions
author strongly prefers alternatives to C for first-language teaching
fork example exposes the danger of copying syntax without understanding effects
an expert may no longer notice the mental model a beginner is missing
author's closing concern is teaching habits that obscure effects
PROGRAMS = match loop_side_effects select-check-process wait fork
PROGRAMS_PASCAL = match_pas side_effects loop_side_effects_pas
CFLAGS = -g -Wall -O0 -ansi -pedantic
all: $(PROGRAMS) $(PROGRAMS_PASCAL)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
$(PROGRAMS_PASCAL): %: %.pas
fpc $^
clean:
rm -f *.o $(PROGRAMS) $(PROGRAMS_PASCAL)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void fork0()
{
fork();
if (fork() == 0) {
sleep(2);
printf("child\n");
exit(0);
}
}
void wait0()
{
int pid;
while ((pid = wait(NULL)) != -1)
printf("%d\n", pid);
}
int main()
{
fork0();
wait0();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void wrong(char *dest, const char *src)
{
while ((*dest++ = *src++));
}
void correct(char *dest, const char *src)
{
for (; *src; src++, dest++)
*dest = *src;
*dest = 0;
}
int main()
{
const char *src = "hello";
char *dest = malloc(strlen(src) + 1);
char *dest2 = malloc(strlen(src) + 1);
wrong(dest, src);
printf("%s %s\n", src, dest);
correct(dest2, src);
printf("%s %s\n", src, dest2);
free(dest);
free(dest2);
return 0;
}
program loop_side_effects_pas;
procedure correct(var dest: string; src: string);
var
i: integer;
begin
SetLength(dest, length(src));
for i := 1 to length(src) do
dest[i] := src[i]
end;
var
src, dest: string;
begin
src := 'hello';
correct(dest, src);
writeln(src, ' ', dest)
end.
#include <stdio.h>
int match(const char *p, const char *s)
{
switch (*p) {
case 0:
return *s == 0;
case '*':
return match(p + 1, s) || (*s && match(p, s + 1));
default:
return *s && (*s == *p || *p == '?') ? match(p + 1, s + 1) : 0;
}
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s pattern string\n", argv[0]);
return 1;
}
puts(match(argv[1], argv[2]) ? "yes" : "no");
return 0;
}
program match;
function MatchIdx(var p, s: string; i, j: integer): boolean;
begin
if i > length(p) then
MatchIdx := j > length(s)
else if p[i] = '*' then
MatchIdx := MatchIdx(p, s, i + 1, j) or
((j <= length(s)) and MatchIdx(p, s, i, j + 1))
else if (j <= length(s)) and ((s[j] = p[i]) or (p[i] = '?')) then
MatchIdx := MatchIdx(p, s, i + 1, j + 1)
else
MatchIdx := false
end;
function Match(p, s: string): boolean;
begin
Match := MatchIdx(p, s, 1, 1)
end;
begin
if ParamCount <> 2 then begin
writeln(ErrOutput, 'usage: ', ParamStr(0), ' pattern string');
halt(2)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
#include <stdio.h>
void process(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended;
while (1 == fscanf(f, "%d", &n)) {
sum += n;
count++;
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
void process1(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended, res;
res = fscanf(f, "%d", &n);
while (res == 1) {
sum += n;
count++;
res = fscanf(f, "%d", &n);
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
void process2(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended, res;
while (1) {
res = fscanf(f, "%d", &n);
if (res != 1)
break;
sum += n;
count++;
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
int main(int argc, char **argv)
{
FILE *f = stdin;
if (argc > 1) {
f = fopen(argv[1], "r");
if (!f) {
perror(argv[1]);
return 1;
}
}
process2(f);
if (f != stdin)
fclose(f);
return 0;
}
program side;
function f(x: integer) : integer;
begin
writeln(x);
f := x * x
end;
var
a: integer;
m: array [1..100] of integer;
begin
a := f(15) + 2;
m[f(5) - 3] := 7
end.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/wait.h>
void wait0()
{
while (wait(NULL) != -1)
{}
}
void wait1()
{
while (~wait(NULL));
}
void wait2()
{
int pid;
do {
pid = wait(NULL);
} while (pid != -1);
}
int main()
{
int pid;
pid = fork();
if (pid == 0) {
sleep(2);
printf("finished child\n");
exit(0);
}
wait2();
printf("finished parent\n");
return 0;
}
Languages can be compared as delivery tools or as notations for expressing solutions. Concise source matters alongside debugging, dependencies, deployment, and the target environment; neither viewpoint alone answers every practical choice.
many languages exist, but no single best language serves every purpose
two perspectives emphasize different criteria
tool-centered view includes the implementation and deployment environment
notation-centered view emphasizes expressing the solution itself
author warns against confusing abstraction with lack of understanding
concise source is only one comparison criterion
author prefers tools that impose few requirements on the end user
later chapter examines compilation and interpretation as mental models
Treating a condition as a value simplifies boolean results and exposes a small but useful mental model. Explicit comparisons remain clearer when a function's result carries meaning beyond true or false.
condition can itself be a computed value
explicit comparison remains useful when zero is a nonboolean result
"condition as value" is a small but consequential mental model
PROGRAMS = paradigms
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include <stdlib.h>
int is_equal_bad(int a, int b)
{
if (a == b)
return 1;
else
return 0;
}
int is_equal_good(int a, int b)
{
return a == b;
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s <number 1> <number 2>\n", argv[0]);
return 1;
}
puts(is_equal_good(atoi(argv[1]), atoi(argv[2])) ? "yes" : "no");
return 0;
}
A callback supplies behavior for another component to invoke under its own timing and ordering rules. User data can preserve client state, but the interface must also define lifetimes and when callbacks may occur.
callback supplies behavior for another subsystem to invoke
client gives the service a function to call when appropriate
callbacks change how control flow is perceived
practice with higher-order functions or event systems can make this model familiar
client/server roles also exist inside one program
Explicit-state programming stores progress between short steps instead of preserving it inside a blocking call. An external driver supplies events or advance requests, letting a parser, traversal, or GUI resume without monopolizing the event loop.
Etude 9.07 matches wildcards without recursion. The state is
explicit: the position after the last *, and where in the
string that star's current attempt began. On a mismatch, the matcher
returns to that state and lets the star take one more character:
#include <stdio.h>
int match(const char *pat, const char *str)
{
const char *star_loc = NULL;
const char *str_save = NULL;
while (*str) {
if (*pat == '*') {
star_loc = pat;
pat = star_loc + 1;
str_save = str;
} else if (*str == *pat || *pat == '?') {
pat++;
str++;
} else if (star_loc) {
pat = star_loc + 1;
str_save++;
str = str_save;
} else {
return 0;
}
}
while (*pat == '*')
pat++;
return *pat == 0;
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <pattern> <string>\n", argv[0]);
return 1;
}
if (match(argv[1], argv[2]))
printf("matched\n");
else
printf("does not match\n");
return 0;
}
matched
GUI libraries can hide the main event loop
long handlers make other work wait
handler must return within the application's response-time budget
explicit-state programming represents progress between events
explicit states also arise outside interactive event loops
state representation replaces saved execution position
book's strict step model performs one transition at a time
state-machine style is an imperative model with explicit transition rules
represent state as one coherent set of data
divide operation into clearly separated steps
step can update state and produce output actions
next action depends on the current state and the supplied event
caller need not run the machine continuously in a loop
PROGRAMS = keys
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
static void insert(struct node **p, int key)
{
while (*p)
p = key < (*p)->key ? &(*p)->left : &(*p)->right;
*p = malloc(sizeof(**p));
if (!*p) {
perror("malloc");
exit(1);
}
(*p)->key = key;
(*p)->left = NULL;
(*p)->right = NULL;
}
static void destroy(struct node *t)
{
if (!t)
return;
destroy(t->left);
destroy(t->right);
free(t);
}
/* automaton: in-order walk, one key per step */
enum { max_depth = 64 };
struct walker {
const struct node *stack[max_depth];
int top;
};
static void push_left(struct walker *w, const struct node *t)
{
for (; t && w->top < max_depth; t = t->left) {
w->stack[w->top] = t;
w->top++;
}
}
static void walker_init(struct walker *w, const struct node *root)
{
w->top = 0;
push_left(w, root);
}
/* no side effects: only looks at the state */
static int walker_empty(const struct walker *w)
{
return w->top == 0;
}
/* one step: returns the next key; call only if !walker_empty(w) */
static int walker_next(struct walker *w)
{
const struct node *t;
w->top--;
t = w->stack[w->top];
push_left(w, t->right);
return t->key;
}
/* pretend a network client asks for a key */
static void serve_client(struct walker *w, const char *name)
{
int key;
if (walker_empty(w)) {
printf("%s: no keys left\n", name);
return;
}
key = walker_next(w);
printf("%s gets key %d\n", name, key);
}
int main(void)
{
int keys[] = { 50, 20, 70, 10, 30 };
struct node *t = NULL;
struct walker w;
size_t i;
for (i = 0; i < sizeof(keys) / sizeof(*keys); i++)
insert(&t, keys[i]);
walker_init(&w, t);
serve_client(&w, "alice");
printf("... other work, time passes ...\n");
serve_client(&w, "bob");
serve_client(&w, "carol");
printf("... more work ...\n");
for (i = 0; i < 3; i++)
serve_client(&w, "dave");
destroy(t);
return 0;
}
Metaprogramming generates or manipulates program code, adding a second level of reasoning about what the generated program will do. Macros and C++ templates provide examples with different expressive capabilities.
metaprogramming writes code that produces or manipulates program code
a generator can produce another program or one module of it
macros are an earlier example of this idea
C++ templates and later interpreted-language facilities extend the examples
Previous: Inside the Kernel Reading map Next: C++ Programming
Comments