LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 7

A counter module with private state and a reset in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
main.c
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links