LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 1

Count how many times a function is called in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Make a function that reports how many times it has been called, using a static local.

Solution
main.c
#include <stdio.h>

void greet(const char *name) {
    static int calls = 0;            /* survives between calls */
    calls++;
    printf("Hello, %s! (call %d)\n", name, calls);
}

int main(void) {
    greet("Asha");
    greet("Ravi");
    greet("Meera");
    return 0;
}

Output Verified by compiling and running

Hello, Asha! (call 1)
Hello, Ravi! (call 2)
Hello, Meera! (call 3)

The counter is private to greet() but outlives each call. A global would also work, but any other function could then change it.

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