Coverage
- C course
- Advanced
- Lesson 70/83
- 5 min
Learn code coverage measurement.
Coverage
Code coverage measures how much of the source code the tests exercise. The gcov and lcov tools ship with GCC; they give execution counts for each line and branch.
In this lesson we count branches manually with a coverage_counter; this is a simplified view of what gcov does behind the scenes. The sign(int n) function has three branches: positive, negative and zero. If a test exercises only one branch, coverage is 1/3.
Counting branches
You declare a coverage_counter global variable. The sign function increments the counter in each branch; you see which branches ran. Test coverage is the ratio of executed branches to total branches.
Example: int sign(int n) { if (n > 0) { coverage_counter++; return 1; } if (n < 0) { coverage_counter++; return -1; } coverage_counter++; return 0; }. Calling sign(5) exercises only the first branch; the counter becomes 1. For full coverage you must test all three branches.
Practice sign with coverage counter
Declare a global int coverage_counter = 0;. Write int sign(int n): if n > 0 do { coverage_counter++; return 1; }, if n < 0 do { coverage_counter++; return -1; }, else coverage_counter++; return 0;. In main compute int r = sign(5); and print printf("kapsam: %d\n", coverage_counter); and printf("sign: %d\n", r);.
Starter code
#include <stdio.h>
// Declare a global coverage counter (start at 0)
// Write sign: increment counter in each branch
// main: call sign(5) and print coverage and sign value
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int coverage_counter = 0;
int sign(int n) {
if (n > 0) { coverage_counter++; return 1; }
if (n < 0) { coverage_counter++; return -1; }
coverage_counter++;
return 0;
}
int main(void) {
int r = sign(5);
printf("kapsam: %d\n", coverage_counter);
printf("sign: %d\n", r);
return 0;
}Expected output
kapsam: 1 sign: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does gcov measure?
- Memory usage
- Code coverage Correct answer
- File size
- CPU speed
Explanation: gcov gives execution counts for each line and branch.
2 Match coverage tools
| Term | Meaning |
|---|---|
gcov |
Line counter |
lcov |
HTML report |
sign |
Three-branch fn |
coverage_counter |
Manual counter |
3 sign positive branch
if (n > 0) { coverage_counter++; return ____; }
if (n > 0) { coverage_counter++; return 1; }
Explanation: sign returns 1 for a positive number.