Functions
- C course
- Beginner
- Lesson 114/116
- 6 min
Write business rules with functions and conditional logic.
The print_book function
To avoid printing books repeatedly, you define a print_book function. This keeps the code organized and free of repetition.
void print_book(struct Book b) {
printf("%s %d\n", b.title, b.year);
}This function takes a struct Book and prints its title and year. The void return type means it returns no value. The function can be called anywhere in the catalog; this prevents code duplication.
Function call
You call the print_book function you defined inside main. The call uses the function name and the argument in parentheses.
struct Book b = {"Suç ve Ceza", 1866};
print_book(b);
// "Suç ve Ceza 1866"Here b is passed by copying into the function; the function works on its own copy. This is pass by value. For large structs using a pointer may be more efficient; but for now pass by value is enough.
Practice Define and call print_book
Define void print_book(struct Book b); inside it print b.title and b.year with printf. In main call print_book(b).
Starter code
#include <stdio.h>
struct Book {
char title[32];
int year;
};
// Define the print_book function: takes a Book and prints with printf
int main(void) {
struct Book b = {"War and Peace", 1869};
// Call the print_book function
return 0;
}Sample solution
void print_book(struct Book b) {
printf("%s %d\n", b.title, b.year);
}
print_book(b);Expected output
War and Peace 1869
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match piece to task
| Term | Meaning |
|---|---|
void |
Returns no value |
struct Book b |
Parameter |
b.title |
Member access |
printf |
Produces output |
2 What is the return type of the print_book function?
- int
- void Correct answer
- char *
- struct Book
Explanation: print_book returns no value; its return type is void.
3 Fill in the blank: function definition
____ print_book(struct Book b) {
printf("%s %d\n", b.title, b.year);
}
void print_book(struct Book b) {
printf("%s %d\n", b.title, b.year);
}
Explanation: void print_book declares a function with no return value.