Question 7
Back to Exercise
Create a visitor counter whose value lives in a file-scope static variable, with functions to increment, read and reset it.
Solution
#include <stdio.h>
static unsigned visitors = 0; /* hidden from other files */
void visitor_arrived(void) { visitors++; }
unsigned visitor_count(void) { return visitors; }
void visitor_reset(void) { visitors = 0; }
int main(void) {
for (int i = 0; i < 4; i++)
visitor_arrived();
printf("today: %u\n", visitor_count());
visitor_reset();
visitor_arrived();
printf("after reset: %u\n", visitor_count());
return 0;
}
today: 4 after reset: 1
Other files can only use the three functions, never the variable itself. If the rules change (say, a daily limit), only this file needs editing.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!