C
Checking out
Write the checkout flow with Checkout and Return functions.
The checkout flow
A book's borrowed state lives in the borrowed field: 0 on shelf, 1 checked out. The checkout function lends the book: b->borrowed = 1;. The return_book function returns it: b->borrowed = 0;.
Both check the current state first. checkout returns 0 if already borrowed; otherwise sets 1 and returns 1. return_book returns 0 if already on shelf; otherwise sets 0 and returns 1. These return values let the caller check the outcome. A real library also records the member id; we keep it simple here.
The return_book function
return_book is the inverse of checkout. First it checks if (!b->borrowed) to see if it's on shelf; if so it returns 0 (already returned). Otherwise it sets b->borrowed = 0; and returns 1.
This symmetric design makes state transitions safe. A book can't be returned twice or lent twice by accident. In main you can call checkout(&lib.books[0]); and print the state with printf("%d\n", lib.books[0].borrowed);. Test return_book the same way.
Exercise Add checkout and return_book
Add int checkout(Book *b) with if (b->borrowed) return 0; b->borrowed = 1; return 1;. Add int return_book(Book *b) with if (!b->borrowed) return 0; b->borrowed = 0; return 1;. In main call checkout(&lib.books[0]);, printf("%d\n", lib.books[0].borrowed);, return_book(&lib.books[0]);, printf("%d\n", lib.books[0].borrowed);.
Show example solution
#include <stdio.h>
#include <string.h>
typedef struct {
char title[64];
int year;
int borrowed;
} Book;
typedef struct {
char name[64];
int id;
} Member;
typedef struct {
Book books[10];
int count;
} Library;
void library_init(Library *lib) {
lib->count = 0;
}
void library_add(Library *lib, Book b) {
lib->books[lib->count++] = b;
}
void print_book(Book *b) {
printf("Book: %s (%d)\n", b->title, b->year);
}
int checkout(Book *b) {
if (b->borrowed) return 0;
b->borrowed = 1;
return 1;
}
int return_book(Book *b) {
if (!b->borrowed) return 0;
b->borrowed = 0;
return 1;
}
int main(void) {
Library lib;
library_init(&lib);
Book b1 = {"C Tutorial", 2024, 0};
library_add(&lib, b1);
checkout(&lib.books[0]);
printf("%d\n", lib.books[0].borrowed);
return_book(&lib.books[0]);
printf("%d\n", lib.books[0].borrowed);
return 0;
}
Test yourself
-
Complete the checkout body
int checkout(Book *b) {
if (b->borrowed) return 0;
b->borrowed = ____;
return 1;
}
Show answer
int checkout(Book *b) {
if (b->borrowed) return 0;
b->borrowed = 1;
return 1;
}
-
What does checkout return for an already-borrowed book?
- 1 (success)
- 2 (warning)
- -1 (error)
- 0 (failure)
Show answer
0 (failure) — checkout returns 0 for a borrowed book; the operation fails.
-
Match borrowed states
- borrowed=0
- On shelf
- borrowed=1
- Checked out
- checkout returns 1
- Successful checkout
- return_book returns 0
- Already on shelf
Next lesson: Search and filter