Home > Software engineering >  how to count number of a specific function be called at compile time
how to count number of a specific function be called at compile time

Time:07-09

A program is divided into N functions.

Like the following code snippets: after calling each function, I wanna show the progress count/N

how to count N at compile time ?

#include <iostream>

using namespace std;

double progress()
{
    int const total = 4; // how to get 4?
    static int counter = 0;
    return static_cast<double>(counter  ) / static_cast<double>(total);
}

int main()
{
    cout << progress() << endl; // 0.25
    cout << progress() << endl; // 0.5
    cout << progress() << endl; // 0.75
    cout << progress() << endl; // 1.0
    return 0;
}

I tried constexpr function, but cannot increment a variable.

CodePudding user response:

Imagine the following code:

int main() {
    cout << "N = ";
    int N;
    cin >> N;
    for (int i = 0; i < N;   i) cout << progress() << endl;
}

There is absolutely no way, the compiler can know how many times the function will be executed. So you need to determine the number using the logic of your data.

If you want to know how many times you call progress without loops, recursions, conditions etc., the only way I can think of is using external tool on the source file. E.g.

cat source.cpp | grep -o progress() | wc -l

Just remember to subtract 1 from the result, which accounts for the function definition.

CodePudding user response:

Unfortunately, you cannot.

This is not something that can be determined at compile time.

See https://en.wikipedia.org/wiki/Halting_problem

  • Related